Posted in

INHERITANCE INTERVIEW QUESTIONS IN JAVA

1. What is inheritance in Java?

Inheritance in Java is a feature that allows one class (called a subclass or child class) to inherit properties and methods from another class (called a superclass or parent class). It promotes code reusability and supports polymorphism.

2. What are the types of inheritance supported in Java?

The types of inheritance supported in Java:

  1. Single Inheritance – A class inherits from one superclass.
  2. Multilevel Inheritance – A class inherits from a subclass, forming a chain.
  3. Hierarchical Inheritance – Multiple classes inherit from one superclass.
  4. Hybrid Inheritance – Achieved using interfaces (since Java doesn’t support multiple inheritance with classes).

     Note:
          Java does not support multiple inheritance with classes to avoid ambiguity, but it supports it using interfaces.

3. What is single inheritance?

   Single inheritance in Java means a class inherits from one superclass only. It allows the subclass to access the methods and fields of the parent class, promoting code reuse.

Example :

          class Animal {
            void eat() {
              System.out.println(“Animal eats”);
          }
}
class Dog extends Animal {
    void bark() {
        System.out.println(“Dog barks”);
    }
}

4. What is multiple inheritance?

   Multiple inheritance is when a class inherits features from more than one parent class.

  • Java does not support multiple inheritance with classes to avoid ambiguity (like the diamond problem).
  • However, Java supports multiple inheritance throughinterfaces.

 Example using interfaces:

  interface A {
    void show();
}
interface B {
    void display();
}
class C implements A, B {
    public void show() {
        System.out.println(“Show from A”);
    }
    public void display() {
        System.out.println(“Display from B”);
    }
}

5. What is the difference between single inheritance and multiple inheritance?

Feature Single Inheritance Multiple Inheritance
DefinitionInherits from one superclassInherits from more than one superclass or interface
Class SupportSupported directly with classesNot supported with classes
Interface SupportNot neededAchieved using interfaces in Java
ComplexitySimple and easy to implementCan be complex due to ambiguity (e.g., diamond problem)
Exampleclass B extends Aclass C implements A, B (interfaces)

6. Can you explain the difference between a base class and a derived class?

Here’s the difference between a base class and a derived class in Java:

  • Base Class (also called superclass or parent class):
    The class that is inherited from. It contains common properties and methods.
  • Derived Class (also called subclass or child class):
    The class that inherits from the base class. It can use and extend the functionality of the base class.

7. What are the advantages of using inheritance?

The advantages of using inheritance in Java:

  1. Code Reusability – Common code written in the base class can be reused by derived classes.
  2. Improved Code Organization – Helps structure programs logically using hierarchical relationships.
  3. Extensibility – New features can be added to existing code with minimal changes.
  4. Polymorphism Support – Enables dynamic method binding, allowing flexible and maintainable code.
  5. Reduced Redundancy – Avoids code duplication by sharing common behavior across classes.

8. What is the significance of the super keyword in inheritance?

      The super keyword in Java is used in inheritance to refer to the parent class (superclass).

Significance:

  1. Access parent class methods – Call a method from the superclass.
  2. Access parent class constructor – Call the superclass constructor using super().
  3. Access parent class variables – Especially when they are hidden by subclass variables.

Example:

     class Animal {
    void eat() {
        System.out.println(“Animal eats”);
    }
}
class Dog extends Animal {
    void eat() {
        super.eat(); // Calls Animal’s eat()
        System.out.println(“Dog eats”);
    }
}

9. What happens if a subclass does not have a constructor but the base class does?

If a subclass does not have a constructor, Java automatically provides a default constructor.

  • If the base class has a no-argument (default) constructor, the subclass will compile and work fine.
  • But if the base class only has a parameterized constructor, and the subclass doesn’t explicitly call it using super(), a compile-time error will occur.
  • The subclass must call the base class’s constructor explicitly using super(arguments).

Example:

class Animal {
    Animal(String name) {
        System.out.println(“Animal: ” + name);
    }
}
class Dog extends Animal {
    Dog() {
        super(“Dog”);
    }
}

10. Can a subclass have the same method name as the base class? If yes, how does method overriding work in this case?

           Yes, a subclass can have the same method name as the base class — this is called method overriding in Java.

How method overriding works:

  1. The subclass provides a new implementation of a method already defined in the superclass.
  2. The method must have the same name, return type, and parameters.
  3. At runtime, the subclass version is called (polymorphism), even if the object is referenced by a superclass type.

11. What is method overriding in inheritance?

Method overriding in inheritance occurs when a subclass provides its own implementation of a method that is already defined in the base class (superclass).

Key points of method overriding:

  • The method in the subclass must have the same name, return type, and parameters as the method in the base class.
  • It allows the subclass to provide specific behavior while maintaining the same method signature.
  • Runtime polymorphism is achieved through method overriding, where the method call is resolved at runtime based on the object’s actual type.

12. Can a derived class access private members of the base class? Why or why not?

     No, a derived class cannot directly access private members of the base class.

Reason:

  • Private members in a class are only accessible within that class. They are not inherited by derived classes.
  • The derived class can access private members indirectly only through public or protected methods provided by the base class (like getters and setters).

13. What is the difference between “extends” and “implements” in inheritance ?

Features extends implements
Used forInheriting from a class (for subclassing).Implementing an interface (providing functionality).
Type of inheritanceSingle inheritance (can only extend one class).Multiple inheritance (can implement multiple interfaces).
UsageA subclass inherits methods and fields from the base class.A class agrees to implement all methods declared in the interface.
Method ImplementationCan inherit and override methods from the base class.Must provide implementations for all methods declared in the interface.

14. What is multilevel inheritance?

    Multilevel inheritance in Java occurs when a class is derived from another class, and that class is itself derived from another class, forming a chain of inheritance.

Key points:

  • It involves three or more classes, where the base class is inherited by a derived class, and that derived class is inherited by another class, and so on.
  • The subclass in the chain can inherit methods and fields from all its ancestor classes.

Example :

   class Animal {  // Base class
    void eat() {
        System.out.println(“Animal eats”);
    }
}
class Dog extends Animal {  // Derived from Animal
    void bark() {
        System.out.println(“Dog barks”);
    }
}
class Puppy extends Dog {  // Derived from Dog (and indirectly from Animal)
    void sleep() {
        System.out.println(“Puppy sleeps”);
    }
}
public class Test {
    public static void main(String[] args) {
        Puppy p = new Puppy();
        p.eat();   // Inherited from Animal
        p.bark();  // Inherited from Dog
        p.sleep(); // Defined in Puppy
    }
}

15. What is hierarchical inheritance in Java?

Hierarchical inheritance in Java occurs when multiple classes inherit from a single base class. In this type of inheritance, one parent class provides a common set of properties and methods, which are inherited by multiple child classes.

Key points:

  • One base class is extended by two or more subclasses.
  • It allows code reusability for common functionality shared by all subclasses.

Example:

class Animal {  // Base class
    void eat() {
        System.out.println(“Animal eats”);
    }
}
class Dog extends Animal {  // Derived class 1
    void bark() {
        System.out.println(“Dog barks”);
    }
}
class Cat extends Animal {  // Derived class 2
    void meow() {
        System.out.println(“Cat meows”);
    }
}
public class Test {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat();  // Inherited from Animal
        dog.bark(); // Defined in Dog
        Cat cat = new Cat();
        cat.eat();  // Inherited from Animal
        cat.meow(); // Defined in Cat
    }
}   

16. What happens when a method is defined in the base class in a hierarchical inheritance structure in Java?

          In hierarchical inheritance, a method defined in the base class is inherited by all subclasses. Each subclass can use the method directly or override it to provide its own implementation.If not overridden, the base class version is executed. This promotes code reuse and flexibility in behavior. Overridden methods enable runtime polymorphism in Java.

17. What are the advantages of using hierarchical inheritance in Java?

The advantages of using hierarchical inheritance in Java are:

  • Promotes code reusability by allowing multiple subclasses to share common code from a single superclass.
    • Improves modularity and organization of code.
    • Supports runtime polymorphism, allowing dynamic method dispatch.
    • Simplifies maintenance and updates by centralizing shared behavior.
    • Enables easy extension of functionality through subclassing.

18. What are the possible issues that might arise when using hierarchical inheritance in Java?

Some possible issues with hierarchical inheritance in Java are:

  1.  Code duplication can occur if subclasses implement similar logic differently.
  2. Tight coupling between base and subclasses can reduce flexibility.
  3. Overriding errors may lead to unexpected behavior if not handled carefully.
  4. Difficult to manage when the hierarchy becomes too deep or complex.
  5. Changes in the superclass can impact all subclasses, possibly introducing bugs.

19. What is the role of polymorphism in hierarchical inheritance in Java?

The role of Polymorphism in Hierarchical Inheritance in Java :

  1. Polymorphism allows one interface, many implementations across subclasses.
  2. It enables a parent class reference to point to any of its subclass objects.
  3. Method overriding allows each subclass to define its own version of a method.
  4. At runtime, the actual object type determines which method is executed.
  5. This supports dynamic behavior and enhances flexibility and maintainability.

20. Can a subclass inherit from multiple classes in hierarchical inheritance in Java?

No, a subclass cannot inherit from multiple classes in hierarchical inheritance in Java because Java does not support multiple inheritance with classes to avoid ambiguity (like the Diamond Problem). Instead, Java supports multiple inheritance through interfaces.

21. How do abstract classes and interfaces fit into hierarchical inheritance in Java?

 In hierarchical inheritance in Java, abstract classes and interfaces play important roles:

  1. Abstract classes can serve as base classes in hierarchical inheritance, providing shared code and abstract methods.
  2. Subclasses must implement abstract methods or be declared abstract themselves.
  3. Interfaces allow multiple inheritance of type and behavior in the hierarchy.
  4. A class can extend one abstract class and implement multiple interfaces.
  5. They promote code reuse, flexibility, and loose coupling in hierarchical designs.

22. What happens if a method in the parent class is overridden in one subclass but not in others in hierarchical inheritance in Java?

In hierarchical inheritance, if a method in the parent class is overridden in one subclass but not in others, then:

  • The subclass that overrides the method will execute its own version of the method.
  • The other subclasses that don’t override the method will inherit and use the parent class version.
  • This demonstrates runtime polymorphism, where the method that gets executed depends on the actual object type, not the reference type.
  • It allows each subclass to have custom behavior while others retain the default implementation.
  • There’s no error or conflict — Java handles it cleanly via method overriding rules.

23. What is the role of the protected access modifier in inheritance?

The protected access modifier allows a member (variable or method) to be:

  • Accessible within the same package (like default/package-private).
  • Accessible in subclasses, even if they are in different packages.

  In inheritance, protected enables subclasses to access and reuse fields or methods from the parent class while still restricting access from non-related classes. This strikes a balance between encapsulation and inheritance, giving controlled visibility to subclasses.

24. Explain the concept of inheritance with respect to “is-a” and “has-a” relationships?

    In inheritance:

   1. “is-a” Relationship:
Inheritance represents an “is-a” relationship when a subclass is a type of the parent class. This means the subclass inherits the characteristics (fields and methods) of the parent class and is a specialized version of it.

  • Example: A Dog is a type of Animal. So, Dog inherits from Animal.

     2. “has-a” Relationship:
The “has-a” relationship is not directly related to inheritance but is commonly used in composition (when one class contains objects of another class). Here, one class has an instance of another class as a member.

  • Example: A Car has-a Engine. The Car class may contain an Engine object but doesn’t necessarily extend Engine.

25. What is the difference between composition and inheritance?

                   Aspect            Inheritance            Composition
       DefinitionA subclass extends a superclass and inherits its behavior.A class has an instance of another class as a member.
      RelationshipRepresents an “is-a” relationship (e.g., Dog is an Animal).Represents a “has-a” relationship (e.g., Car has an Engine).
      CouplingCreates tight coupling between superclass and subclass.Promotes loose coupling between classes.
       FlexibilityLess flexible, changes in the superclass affect all subclasses.More flexible, as classes can change without affecting others.
       Code ReuseReuse through method inheritance and overriding.Reuse through object references and delegation.

26. Can you explain “constructor chaining” in inheritance?

Constructor chaining refers to the process where a constructor in a subclass calls a constructor of its superclass. This allows the initialization of the inherited properties of the superclass before the subclass’s own properties are initialized.

Key Points:

  1. Superclass constructor is called before the subclass constructor.
  2. The subclass can explicitly call a superclass constructor using super(). If super() is not used, Java implicitly calls the default constructor of the superclass (if available).
  3. If the superclass does not have a no-argument constructor, the subclass must explicitly call one of the superclass constructors.

27. What is the impact of inheritance on the performance of an application?

Inheritance can impact performance in the following ways:

  1. Method Lookup: Slight overhead due to checking both subclass and superclass during method calls.
  2. Memory Usage: Inherited fields increase object size, but the impact is usually minimal.
  3. Polymorphism Overhead: Dynamic method dispatch adds minor runtime overhead.
  4. Complexity: Deep hierarchies may lead to harder-to-maintain code, affecting long-term performance.

28. What is multiple inheritance in Java?

Multiple inheritance in Java refers to the concept of a class inheriting from more than one superclass. However, Java does not support direct multiple inheritance through classes to prevent issues like ambiguity and method conflicts. Instead, Java achieves multiple inheritance through interfaces. A class can implement multiple interfaces, inheriting their abstract methods, and then providing its own implementation for those methods. This approach avoids the complexities of multiple inheritance while still allowing a class to adopt behaviors from multiple sources.

29. Why doesn’t Java support multiple inheritance directly?

       Java does not allow multiple inheritance directly through classes to prevent problems such as:

  1. Ambiguity: If two parent classes have the same method, the compiler would be unable to determine which method to invoke, causing conflicts.
  2. Complexity: Multiple inheritance can result in complicated and hard-to-manage class hierarchies.

Instead, Java supports multiple inheritance via interfaces, allowing a class to implement multiple interfaces. This approach avoids ambiguity and provides the flexibility of inheritance, while keeping the design simple and free from the issues associated with multiple inheritance of classes.

30. How does Java avoid the ambiguity problem in multiple inheritance?

Java avoids multiple inheritance issues by allowing classes to implement multiple interfaces instead of extending multiple classes. If multiple interfaces have the same method, the class must override it, preventing ambiguity. This resolves the diamond problem and ensures clear, conflict-free behavior.

31. What are the advantages of using interfaces to implement multiple inheritance in Java?

The advantages of using interfaces for multiple inheritance in Java:

  1. Avoids Ambiguity: Interfaces prevent method conflict issues seen in class-based multiple inheritance.
  2. Flexibility: A class can implement multiple interfaces, allowing it to adopt multiple behaviors.
  3. Loose Coupling: Promotes a more modular and maintainable code structure.
  4. Supports Polymorphism: Interfaces enable dynamic method binding at runtime.
  5. Design Clarity: Encourages separation of concerns and cleaner system design.

32. What is the “diamond problem” in the context of multiple inheritance, and how does Java resolve it?

               The diamond problem occurs in multiple inheritance when a class inherits the same method from two different parent classes, leading to ambiguity about which method to use.

 For example:

     A
    / \
   B   C
    \ /
     D
 If Class A has a method, and Class B and Class C both inherit from A and override the method, and then  Class D inherits from both B and C — it’s unclear which version of the method D should inherit. 

               In Java, the diamond problem is avoided by prohibiting multiple class inheritance. Instead, Java uses interfaces to achieve multiple inheritance. When a class implements multiple interfaces that define the same method, Java requires the class to override and define that method itself. This rule ensures there’s no confusion or conflict, providing a clear andconsistent method implementation.

33. What is the effect of multiple inheritance using interfaces on method resolution order (MRO) in Java?

when a class implements multiple interfaces that contain default methods with the samesignature, the compiler does not automatically decide which one to use. Instead, Java requires the implementing class to override the conflicting method and provide its own implementation. This eliminates ambiguity and makes the method resolution order (MRO) explicit and predictable.

34. What is the difference between interface inheritance and class inheritance in Java?

                    Aspect Class Inheritance          Interface Inheritance
            Keyword Used                extends implements
         Multiple InheritanceNot allowed (only one class can be extended)Allowed (multiple interfaces can be implemented)
        Type of MembersCan have concrete methods and state (fields)Can have abstract methods, default & static methods
ConstructorsCan have constructorsCannot have constructors
Access ModifiersSupports all access modifiersMethods are public and abstract by default

35. Can Java’s multiple inheritance mechanism using interfaces be considered a form of composition? Explain why or why not?

    No, Java’s multiple inheritance using interfaces is not considered composition. Interfaces define a contract that a class agrees to implement, enabling inheritance of behavior (through method signatures or default methods). Composition, on the other hand, is when a class contains objects of other classes as members and uses their functionality (a “has-a” relationship). Interface-based inheritance is about what a class can do, while composition is about what a class has.

Leave a Reply

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