inheritance in java

inheritance in java

In this session we’re going to cover most asked interview question about inheritance

E.g:

Q1) what is the inheritance in java
Q2) types of inheritance in java
Q3) what are the advantages of using Inheritance in java
Q4) What are disadvantages of inheritance in java
Q5) What is multiple inheritance in java
Q6) Why is multiple inheritance not supported in java


Q1) what is the inheritance in java

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (subclass or child class) to inherit properties and behaviors from another class (superclass or parent class). The subclass can reuse and extend the functionality of the superclass, promoting code reuse and creating a hierarchical relationship between classes.

In Java, inheritance is implemented using the extends keyword. Here’s a basic example to illustrate inheritance:

inheritance in java

Example# 1

Example
// Parent class (superclass)
class Animal {
    void eat() {
        System.out.println("Animal is eating.");
    }

    void sleep() {
        System.out.println("Animal is sleeping.");
    }

    void move() {
        System.out.println("Animal is moving.");
    }

    void makeNoise() {
        System.out.println("Animal makes a noise.");
    }
}

// Child class (subclass) inheriting from Animal
class Cow extends Animal {
    // Overriding the eat() method
    @Override
    void eat() {
        System.out.println("Cow is grazing.");
    }

    // Overriding the makeNoise() method
    @Override
    void makeNoise() {
        System.out.println("Cow says moo.");
    }
}

public class Main {
    public static void main(String[] args) {
        // Creating an instance of the Cow class
        Cow myCow = new Cow();

        // Accessing methods from both Animal and Cow classes
        myCow.eat();        // Overridden method in Cow
        myCow.sleep();      // Inherited from Animal
        myCow.move();       // Inherited from Animal
        myCow.makeNoise();  // Overridden method in Cow
    }
}
  • The Animal class is the superclass with methods eat(), sleep(), move(), and makeNoise().
  • The Cow class is the subclass that extends Animal. It inherits the methods eat(), sleep(), move(), and makeNoise() from the Animal class and overrides the eat() and makeNoise() methods with its own implementations.
  • The main method demonstrates creating an instance of the Cow class and calling methods from both the Animal and Cow classes.

Key points about inheritance in Java:

  1. Code Reusability: Inheritance promotes code reuse by allowing subclasses to reuse the code of the superclass.
  2. Method Overriding: Subclasses can provide their own implementation for methods inherited from the superclass. This is known as method overriding.
  3. Access to Superclass Members: Subclasses have access to public and protected members of the superclass, allowing them to use or override those members.
  4. Single Inheritance: In Java, a class can extend only one superclass (single inheritance). However, a class can implement multiple interfaces, allowing it to inherit from multiple sources.

Example# 2

Example
// Parent class (superclass)
class Animal {
    void eat() {
        System.out.println("Animal is eating.");
    }

    void sleep() {
        System.out.println("Animal is sleeping.");
    }
}

// Child class (subclass) inheriting from Animal
class Dog extends Animal {
    void bark() {
        System.out.println("Dog is barking.");
    }
}

public class Main {
    public static void main(String[] args) {
        // Creating an instance of the Dog class
        Dog myDog = new Dog();

        // Accessing methods from both Animal and Dog classes
        myDog.eat();    // Inherited from Animal
        myDog.sleep();  // Inherited from Animal
        myDog.bark();   // Specific to Dog
    }
}

In this example:

  • The Animal class is the superclass with methods eat() and sleep().
  • The Dog class is the subclass that extends Animal. It inherits the methods eat() and sleep() from the Animal class and adds its own method bark().
  • The main method demonstrates creating an instance of the Dog class and calling methods from both the Animal and Dog classes.

Example of method overriding in the subclass:

Example
class Cat extends Animal {
    // Method overriding
    @Override
    void eat() {
        System.out.println("Cat is eating.");
    }
}

public class Main {
    public static void main(String[] args) {
        Cat myCat = new Cat();
        myCat.eat();  // Calls the overridden method in Cat class
        myCat.sleep();  // Inherited from Animal class
    }
}

In this example, the Cat class overrides the eat() method inherited from the Animal class with its own implementation.


Q2) types of inheritance in java

In Java, inheritance can be classified into different types based on the relationships between classes. The main types of inheritance are:

1. Single Inheritance:

2. Multilevel Inheritance:

3. Hierarchical Inheritance:

4. Hybrid Inheritance:

5. Multiple Inheritance (through Interfaces):

inheritance in java
1. Single Inheritance:

In single inheritance, a class can extend only one superclass. Java supports single inheritance for classes, meaning a class can have only one direct parent class.

inheritance in java
Example
// Parent class (superclass)
class Animal {
    void eat() {
        System.out.println("Animal is eating.");
    }

    void sleep() {
        System.out.println("Animal is sleeping.");
    }
}

// Child class (subclass) inheriting from Animal
class Dog extends Animal {
    void bark() {
        System.out.println("Dog is barking.");
    }
}

public class Main {
    public static void main(String[] args) {
        // Creating an instance of the Dog class
        Dog myDog = new Dog();

        // Accessing methods from both Animal and Dog classes
        myDog.eat();  // Inherited from Animal
        myDog.sleep();  // Inherited from Animal
        myDog.bark();   // Specific to Dog
    }
}

In this example:

  • Animal is the parent class (superclass) with methods eat() and sleep().
  • Dog is the child class (subclass) that extends Animal. It inherits the methods eat() and sleep() from the Animal class and adds its own method bark().
  • The main method demonstrates creating an instance of the Dog class and calling methods from both the Animal and Dog classes.

This represents a simple example of single inheritance, where a subclass extends a single superclass.

2. Multilevel Inheritance:

In multilevel inheritance, a class serves as a superclass for another class, and that subclass, in turn, becomes the superclass for another class.

inheritance in java

In this example, C inherits from B, which, in turn, inherits from A.

Example
// Grandparent class (superclass)
class Animal {
    void eat() {
        System.out.println("Animal is eating.");
    }

    void sleep() {
        System.out.println("Animal is sleeping.");
    }
}

// Parent class (subclass) inheriting from Animal
class Dog extends Animal {
    void bark() {
        System.out.println("Dog is barking.");
    }
}

// Child class (subclass) inheriting from Dog
class Bulldog extends Dog {
    void guard() {
        System.out.println("Bulldog is guarding.");
    }
}

public class Main {
    public static void main(String[] args) {
        // Creating an instance of the Bulldog class
        Bulldog myBulldog = new Bulldog();

        // Accessing methods from Animal, Dog, and Bulldog classes
        myBulldog.eat();    // Inherited from Animal
        myBulldog.sleep();  // Inherited from Animal
        myBulldog.bark();   // Inherited from Dog
        myBulldog.guard();  // Specific to Bulldog
    }
}

In this example:

  • Animal is the grandparent class (superclass) with methods eat() and sleep().
  • Dog is the parent class (subclass) that extends Animal. It inherits the methods eat() and sleep() from the Animal class and adds its own method bark().
  • Bulldog is the child class (subclass) that extends Dog. It inherits the methods eat(), sleep(), and bark() from the Dog class and adds its own method guard().
  • The main method demonstrates creating an instance of the Bulldog class and calling methods from the Animal, Dog, and Bulldog classes.

This represents a multilevel inheritance scenario where a class extends another class, which in turn is extended by another class.

3. Hierarchical Inheritance:

In hierarchical inheritance, multiple classes inherit from a common superclass. It forms a tree-like structure.

inheritance in java

Both B and C inherit from a common superclass A.

Example
// Parent class (superclass)
class Animal {
    void eat() {
        System.out.println("Animal is eating.");
    }

    void sleep() {
        System.out.println("Animal is sleeping.");
    }
}

// Child class 1 (subclass) inheriting from Animal
class Dog extends Animal {
    void bark() {
        System.out.println("Dog is barking.");
    }
}

// Child class 2 (subclass) inheriting from Animal
class Cat extends Animal {
    void meow() {
        System.out.println("Cat is meowing.");
    }
}

public class Main {
    public static void main(String[] args) {
        // Creating an instance of the Dog class
        Dog myDog = new Dog();
        myDog.eat();    // Inherited from Animal
        myDog.sleep();  // Inherited from Animal
        myDog.bark();   // Specific to Dog

        System.out.println(); // Separating output for clarity

        // Creating an instance of the Cat class
        Cat myCat = new Cat();
        myCat.eat();    // Inherited from Animal
        myCat.sleep();  // Inherited from Animal
        myCat.meow();   // Specific to Cat
    }
}

In this example:

  • Animal is the parent class (superclass) with methods eat() and sleep().
  • Dog is one child class (subclass) that extends Animal. It inherits the methods eat() and sleep() from the Animal class and adds its own method bark().
  • Cat is another child class (subclass) that extends Animal. It inherits the methods eat() and sleep() from the Animal class and adds its own method meow().
  • The main method demonstrates creating instances of both the Dog and Cat classes and calling methods from the Animal, Dog, and Cat classes.

This represents a hierarchical inheritance scenario where multiple classes inherit from a common superclass.

4. Hybrid Inheritance:

Hybrid inheritance is a combination of two or more types of inheritance mentioned above. For example, a class might exhibit multiple inheritance through interfaces, and within those interfaces, it might have multilevel or hierarchical inheritance.

inheritance in java
Example
// Interface with a method
interface Walkable {
    void walk();
}

// Grandparent class (superclass)
class Animal {
    void eat() {
        System.out.println("Animal is eating.");
    }

    void sleep() {
        System.out.println("Animal is sleeping.");
    }
}

// Parent class (subclass) inheriting from Animal and implementing Walkable interface
class Dog extends Animal implements Walkable {
    void bark() {
        System.out.println("Dog is barking.");
    }

    // Implementing the walk() method from the Walkable interface
    @Override
    public void walk() {
        System.out.println("Dog is walking.");
    }
}

// Parent class (subclass) inheriting from Animal and implementing Walkable interface
class Cat extends Animal implements Walkable {
    void meow() {
        System.out.println("Cat is meowing.");
    }

    // Implementing the walk() method from the Walkable interface
    @Override
    public void walk() {
        System.out.println("Cat is walking.");
    }
}

// Child class (subclass) inheriting from Dog
class Bulldog extends Dog {
    void guard() {
        System.out.println("Bulldog is guarding.");
    }
}

public class Main {
    public static void main(String[] args) {
        // Creating an instance of the Bulldog class
        Bulldog myBulldog = new Bulldog();

        // Accessing methods from Animal, Dog, and Bulldog classes
        myBulldog.eat();    // Inherited from Animal
        myBulldog.sleep();  // Inherited from Animal
        myBulldog.bark();   // Inherited from Dog
        myBulldog.walk();   // Implemented from Walkable interface in Dog
        myBulldog.guard();  // Specific to Bulldog
    }
}

In this example:

  • Animal is the grandparent class (superclass) with methods eat() and sleep().
  • Dog and Cat are parent classes (subclasses) that extend Animal and implement the Walkable interface.
  • Bulldog is a child class (subclass) that extends Dog.
  • The Walkable interface defines a walk() method that both Dog and Cat implement.
  • The main method demonstrates creating an instance of the Bulldog class and calling methods from the Animal, Dog, Bulldog, and the Walkable interface.

This example illustrates a combination of single inheritance, interface-based multiple inheritance, and hierarchical inheritance, making it a form of hybrid inheritance.

5. Multiple Inheritance (through Interfaces):

Java does not support multiple inheritance for classes, meaning a class cannot directly extend more than one class. However, multiple inheritance can be achieved through interfaces. Here’s an example demonstrating multiple inheritance through interfaces:

inheritance in java
Example
// Interface with a method
interface Walkable {
    void walk();
}

// Interface with a method
interface Swimmable {
    void swim();
}

// Parent class (superclass)
class Animal {
    void eat() {
        System.out.println("Animal is eating.");
    }

    void sleep() {
        System.out.println("Animal is sleeping.");
    }
}

// Child class (subclass) inheriting from Animal and implementing Walkable and Swimmable interfaces
class Dolphin extends Animal implements Walkable, Swimmable {
    // Implementing the walk() method from the Walkable interface
    @Override
    public void walk() {
        System.out.println("Dolphin is walking on its flippers.");
    }

    // Implementing the swim() method from the Swimmable interface
    @Override
    public void swim() {
        System.out.println("Dolphin is swimming gracefully.");
    }
}

public class Main {
    public static void main(String[] args) {
        // Creating an instance of the Dolphin class
        Dolphin myDolphin = new Dolphin();

        // Accessing methods from Animal, Dolphin, Walkable, and Swimmable
        myDolphin.eat();    // Inherited from Animal
        myDolphin.sleep();  // Inherited from Animal
        myDolphin.walk();   // Implemented from Walkable interface in Dolphin
        myDolphin.swim();   // Implemented from Swimmable interface in Dolphin
    }
}

In this example:

  • Animal is the parent class (superclass) with methods eat() and sleep().
  • Walkable and Swimmable are interfaces with a single method each: walk() and swim().
  • Dolphin is a child class (subclass) that extends Animal and implements both Walkable and Swimmable interfaces.
  • The main method demonstrates creating an instance of the Dolphin class and calling methods from the Animal, Dolphin, Walkable, and Swimmable interfaces.

This illustrates multiple inheritance through interfaces in Java. The Dolphin class inherits from both the Animal class and the Walkable and Swimmable interfaces.

These types of inheritance provide flexibility in designing class hierarchies, and each has its own set of advantages and considerations. Java’s support for single inheritance for classes helps prevent some of the complexities associated with multiple inheritance, while interfaces provide a way to achieve multiple inheritance-like behavior.


Q3) what are the advantages of using Inheritance in java

Inheritance is a fundamental concept in object-oriented programming (OOP), and its usage in Java provides several advantages that contribute to code organization, reuse, and flexibility. Here are some of the key advantages of using inheritance in Java:

1. Code Reusability: Inheritance promotes code reuse by allowing a subclass to inherit the attributes and behaviors (methods) of a superclass. This reduces redundancy in code and encourages a more modular and maintainable codebase.

2. Method Overriding: Subclasses can provide their own implementation for methods inherited from a superclass. This is known as method overriding. It allows for customization of behavior in the subclass while maintaining a common interface defined in the superclass.

3. Polymorphism: Inheritance contributes to polymorphism, which allows objects of a subclass to be treated as objects of the superclass. This enables flexibility in method calls, as the appropriate method is determined at runtime based on the actual type of the object.

4. Extensibility: Inheritance supports extensibility by allowing new classes to be derived from existing classes. New features can be added to a program without modifying existing code. This facilitates the evolution and growth of software systems.

5. Code Organization and Structure: Inheritance helps organize code in a hierarchical and structured manner. The relationships between classes are visually represented in the code, making it easier to understand and maintain.

6. Promotes Modularity: Inheritance encourages the creation of modular, reusable components. Superclasses can be designed to encapsulate common functionality, and subclasses can build upon or specialize that functionality. This modular approach enhances the maintainability of the code.

7. Facilitates Design Patterns: Inheritance plays a crucial role in implementing design patterns, such as the Template Method, Factory Method, and Strategy patterns. Design patterns leverage inheritance to provide solutions to common design problems.

8. Enables Software Development Frameworks: Inheritance is a key feature in the development of software frameworks and libraries. Frameworks provide a structure for building applications, and inheritance allows developers to extend and customize the framework’s functionality.

9. Encourages Code Understanding: Inheritance enhances code readability and understanding by promoting a clear and hierarchical structure. Developers can grasp the relationships between classes and understand how they fit into the overall design.

While inheritance offers these advantages, it’s important to use it judiciously and consider other principles like composition and interface-based programming when designing a system. Overuse of inheritance can lead to tight coupling and make the code less flexible. Therefore, a balanced and thoughtful approach to inheritance is recommended in software development.


Q4) What are disadvantages of inheritance in java

While inheritance in Java provides several advantages, it also comes with certain disadvantages and challenges that developers should be aware of.

Here are some of the key disadvantages of using inheritance:

1. Tight Coupling: Inheritance can lead to tight coupling between classes, especially in cases of deep hierarchies. Changes in the superclass may affect multiple subclasses, and modifications to one class may have unintended consequences on its subclasses.

2. Fragile Base Class Problem: The fragile base class problem occurs when changes to the superclass can inadvertently break functionality in its subclasses. Subclasses may be tightly dependent on the implementation details of the superclass, making maintenance challenging.

3. Inflexibility: Inheritance introduces a static relationship between classes at compile time. This can lead to inflexibility when dynamic changes are required at runtime. Changing the hierarchy may be difficult, and new requirements might necessitate extensive modifications.

4. Limited Code Reuse: While inheritance promotes code reuse, it can also result in the inheritance of unwanted features from the superclass. Subclasses may inherit methods or attributes that are not relevant to their context, leading to a less clean and focused design.

5. Complexity and Understanding: Deep class hierarchies can become complex and difficult to understand, especially for developers who are new to the codebase. Navigating through multiple layers of inheritance may make it challenging to grasp the relationships and responsibilities of each class.

6. Diamond (Multiple) Inheritance Issues: Java does not support multiple inheritance for classes to avoid the diamond problem, where ambiguity arises if a class inherits from two classes that have a common ancestor. While Java supports multiple inheritance through interfaces, it has its own challenges.

7. Performance Overhead: In some cases, there may be a slight performance overhead associated with inheritance due to the need for method dispatch and dynamic binding. This impact is generally negligible, but in performance-critical applications, it might be a consideration.

8. Difficulty in Testing: Testing subclasses in isolation can be challenging, especially when they rely on the behavior of the superclass. Isolating and testing specific components may require additional effort and may not be as straightforward as testing independent classes.

9. Overuse and Misuse: Overuse or misuse of inheritance can lead to a design that is hard to maintain and understand. If inheritance is applied unnecessarily or without careful consideration, it may result in a less flexible and more error-prone system.

To mitigate these disadvantages, it’s essential to follow best practices in object-oriented design, favor composition over inheritance when appropriate, and apply principles like the SOLID principles (especially the Dependency Inversion Principle) to create more maintainable and flexible code. Each design decision should carefully weigh the trade-offs between the benefits and drawbacks of inheritance.


Q5) What is multiple inheritance in java

In Java, multiple inheritance typically refers to a scenario where a class inherits from more than one class. However, Java supports multiple inheritance only through interfaces, not through classes. This means that a class can implement multiple interfaces, each of which can declare a set of methods. In this way, a class can inherit method signatures from multiple sources.

Java does not support multiple inheritance for classes, meaning a class cannot directly extend more than one class. However, multiple inheritance can be achieved through interfaces. Here’s an example demonstrating multiple inheritance through interfaces:

inheritance in java
Example
// Interface with a method
interface Walkable {
    void walk();
}

// Interface with a method
interface Swimmable {
    void swim();
}

// Parent class (superclass)
class Animal {
    void eat() {
        System.out.println("Animal is eating.");
    }

    void sleep() {
        System.out.println("Animal is sleeping.");
    }
}

// Child class (subclass) inheriting from Animal and implementing Walkable and Swimmable interfaces
class Dolphin extends Animal implements Walkable, Swimmable {
    // Implementing the walk() method from the Walkable interface
    @Override
    public void walk() {
        System.out.println("Dolphin is walking on its flippers.");
    }

    // Implementing the swim() method from the Swimmable interface
    @Override
    public void swim() {
        System.out.println("Dolphin is swimming gracefully.");
    }
}

public class Main {
    public static void main(String[] args) {
        // Creating an instance of the Dolphin class
        Dolphin myDolphin = new Dolphin();

        // Accessing methods from Animal, Dolphin, Walkable, and Swimmable
        myDolphin.eat();    // Inherited from Animal
        myDolphin.sleep();  // Inherited from Animal
        myDolphin.walk();   // Implemented from Walkable interface in Dolphin
        myDolphin.swim();   // Implemented from Swimmable interface in Dolphin
    }
}

In this example:

  • Animal is the parent class (superclass) with methods eat() and sleep().
  • Walkable and Swimmable are interfaces with a single method each: walk() and swim().
  • Dolphin is a child class (subclass) that extends Animal and implements both Walkable and Swimmable interfaces.
  • The main method demonstrates creating an instance of the Dolphin class and calling methods from the Animal, Dolphin, Walkable, and Swimmable interfaces.

This illustrates multiple inheritance through interfaces in Java. The Dolphin class inherits from both the Animal class and the Walkable and Swimmable interface


Q6) Why is multiple inheritance not supported in java

Java does not support multiple inheritance for classes, meaning a class cannot directly extend more than one class. The decision to avoid multiple inheritance in Java was made to simplify the language and mitigate potential issues associated with it. Here are some reasons why multiple inheritance is not supported in Java:

1. Diamond Problem: Multiple inheritance introduces the diamond problem, which occurs when a class inherits from two classes that have a common ancestor. If both parent classes provide an implementation for the same method, it becomes ambiguous for the compiler to determine which method should be invoked in the child class. This ambiguity can lead to unpredictable behavior and makes the code harder to understand and maintain.

2. Complexity and Ambiguity: Multiple inheritance can make the class hierarchy more complex and increase the likelihood of conflicts and ambiguities. In the presence of multiple base classes, it becomes challenging to manage and understand the relationships between classes, especially when changes are made.

3. Readability and Maintenance: Supporting multiple inheritance may lead to less readable and more error-prone code. It could result in situations where developers unintentionally inherit behavior from multiple sources, leading to unexpected interactions and difficulties in maintenance.

4. Method Resolution: Resolving method calls becomes more complex in the presence of multiple inheritance. Determining the correct method to call requires a more sophisticated mechanism, and the increased complexity may impact performance.

5. Design Simplicity: Java emphasizes simplicity and readability in its design philosophy. By avoiding multiple inheritance, Java aims to provide a clear and straightforward class hierarchy, making it easier for developers to understand and work with the language.

6. Interface-Based Alternative: While multiple inheritance for classes is not supported, Java provides support for multiple inheritance through interfaces. Interfaces allow a class to implement multiple interfaces, each defining a set of methods. This provides flexibility without introducing some of the complexities associated with multiple inheritance for classes.

Example
interface A {
    void methodA();
}

interface B {
    void methodB();
}

class MyClass implements A, B {
    public void methodA() {
        // Implementation for methodA
    }

    public void methodB() {
        // Implementation for methodB
    }
}

In Java, developers are encouraged to use composition, interfaces, and other design patterns to achieve flexibility and code reuse, while avoiding the challenges associated with multiple inheritance for classes. The absence of multiple inheritance for classes is considered a design choice that aligns with the language’s goals of simplicity, readability, and maintainability.

Here’s a complete example illustrating the use of interfaces in Java to achieve multiple inheritance-like behavior:

Example
// Interface with a method
interface A {
    void methodA();
}

// Interface with a method
interface B {
    void methodB();
}

// Class implementing both interfaces
class MyClass implements A, B {
    @Override
    public void methodA() {
        System.out.println("Executing methodA.");
    }

    @Override
    public void methodB() {
        System.out.println("Executing methodB.");
    }
}

public class Main {
    public static void main(String[] args) {
        // Creating an instance of MyClass
        MyClass myObject = new MyClass();

        // Calling methods from both interfaces
        myObject.methodA();
        myObject.methodB();
    }
}

In this example:

  • A and B are two interfaces, each declaring a single method (methodA() and methodB()).
  • MyClass implements both interfaces A and B and provides concrete implementations for both methods.
  • The main method demonstrates creating an instance of MyClass and calling methods from both interfaces.

This code showcases how a class in Java can implement multiple interfaces to achieve a form of multiple inheritance. The class MyClass inherits the method contracts specified by both interfaces A and B. This approach provides flexibility without introducing the complexities associated with multiple inheritance for classes.

Leave a Reply

Your email address will not be published. Required fields are marked *