Inheritance


Inheritance Interview with follow-up questions

1. What is inheritance in Java?

Inheritance is the OOP mechanism by which a class acquires the fields and methods of another class, modeling an "is-a" relationship. The inheriting class is the subclass/derived class (extends); the one inherited from is the superclass/base class. It enables code reuse and polymorphism (a subclass instance can be used wherever the superclass type is expected, with overridden behavior dispatched at runtime).

class Vehicle { void start() { ... } }
class Car extends Vehicle {            // Car is-a Vehicle
    void openTrunk() { ... }
}
new Car().start();   // inherited

Points interviewers expect: Java supports single inheritance of classes but multiple inheritance of interfaces; every class implicitly extends Object; subclasses can override inherited methods and use super to reach the parent; constructors aren't inherited (the subclass constructor calls super() first).

The important modern caveat: favor composition over inheritance. Deep hierarchies are brittle, so use inheritance only for genuine is-a relationships and prefer has-a composition + interfaces otherwise. Java 17+ adds sealed classes to restrict the permitted subclasses, giving controlled hierarchies that work well with pattern matching — a good thing to mention as current best practice.

↑ Back to top

Follow-up 1

Can you explain with an example?

Sure! Here's an example to illustrate inheritance in Java:

// Superclass
class Animal {
    void eat() {
        System.out.println("The animal is eating.");
    }
}

// Subclass
class Dog extends Animal {
    void bark() {
        System.out.println("The dog is barking.");
    }
}

// Create an instance of the subclass
Dog dog = new Dog();

// Call methods from the superclass
// Output: The animal is eating.
dog.eat();

// Call methods from the subclass
// Output: The dog is barking.
dog.bark();

Follow-up 2

What are the different types of inheritance supported in Java?

Java supports the following types of inheritance:

  1. Single inheritance: A subclass can inherit properties and methods from only one superclass.

  2. Multiple inheritance (through interfaces): A subclass can implement multiple interfaces, allowing it to inherit properties and methods from multiple sources.

  3. Multilevel inheritance: A subclass can inherit properties and methods from a superclass, which in turn can inherit from another superclass, creating a chain of inheritance.

  4. Hierarchical inheritance: Multiple subclasses can inherit properties and methods from a single superclass.

  5. Hybrid inheritance: It is a combination of multiple inheritance and multilevel inheritance.

Follow-up 3

What is the use of 'super' keyword in inheritance?

The 'super' keyword in Java is used to refer to the superclass or base class. It is primarily used to access the members (methods and variables) of the superclass that are hidden or overridden by the subclass. The 'super' keyword can be used to call the superclass constructor, access superclass methods and variables, and invoke the superclass implementation of an overridden method.

Here's an example:

// Superclass
class Animal {
    void eat() {
        System.out.println("The animal is eating.");
    }
}

// Subclass
class Dog extends Animal {
    void eat() {
        super.eat(); // Call the eat() method of the superclass
        System.out.println("The dog is eating.");
    }
}

// Create an instance of the subclass
Dog dog = new Dog();

// Call the eat() method of the subclass
// Output:
// The animal is eating.
// The dog is eating.
dog.eat();

2. How is inheritance implemented in Java?

Java implements inheritance with the extends keyword for classes and implements for interfaces:

class Animal {
    protected String name;
    void eat() { System.out.println(name + " eats"); }
}

class Dog extends Animal {              // class inheritance
    Dog(String n) { super(n = "Dog"); } // super() calls the parent constructor
    @Override void eat() {              // override inherited behavior
        super.eat();                    // optionally call the parent version
        System.out.println("Dog chews");
    }
}

The mechanics interviewers expect:

  • extends — a class inherits the (non-private) fields and methods of one superclass (single class inheritance).
  • super — call the superclass constructor (super(...), must be first statement) or access overridden members (super.method()).
  • Constructor chaining — every subclass constructor invokes a superclass constructor (implicit super() if you don't write one).
  • @Override — annotate overridden methods so the compiler verifies them.
  • implements — inherit a type/contract from interfaces (multiple allowed), supplying implementations (or inheriting default methods).

A current note: every class ultimately extends Object, interfaces can carry default behavior (Java 8+), and you can lock down the hierarchy with sealed/permits (Java 17+). The default-design guidance remains composition over inheritance unless there's a true is-a relationship.

↑ Back to top

Follow-up 1

What is the syntax to inherit a class?

The syntax to inherit a class in Java is as follows:

public class Subclass extends Superclass {
    // subclass code
}

Follow-up 2

Can a class inherit multiple classes in Java?

No, Java does not support multiple inheritance of classes. However, a class can implement multiple interfaces, which provides a form of multiple inheritance.

Follow-up 3

What is the role of constructors in inheritance?

In inheritance, constructors are used to initialize the inherited members of the superclass. When a subclass is created, the constructor of the superclass is automatically called to initialize the inherited members before executing the subclass's constructor code. This ensures that the subclass has access to the inherited members and can properly initialize them.

3. What is the difference between 'extends' and 'implements' keywords in Java?

Both establish inheritance, but of different things:

  • extendsclass inheritance (or interface-to-interface). A class extends one superclass, inheriting its implementation (fields + method bodies). An interface can extends multiple interfaces.
  • implements — a class implements one or more interfaces, agreeing to provide implementations for their abstract methods (it inherits the type/contract, and any default methods).
class Bird extends Animal implements Flyable, Comparable {
    public void fly() { ... }                 // from Flyable
    public int compareTo(Bird b) { ... }      // from Comparable
}

The distinctions interviewers want:

  • A class can extends only one class (single inheritance of state/implementation) but implements many interfaces (multiple inheritance of type) — this is how Java avoids the diamond problem for state while allowing flexible typing.
  • extends inherits concrete behavior and fields; implements historically inherited only contracts, though since Java 8 interfaces can provide default method bodies, blurring the line (but interfaces still can't hold instance state).

A current note: interfaces are usually the better extension point (program to interfaces, easy to mock/test), and sealed interfaces let you constrain implementors. Use extends for genuine is-a class relationships, implements for capabilities a type offers.

↑ Back to top

Follow-up 1

Can an interface extend another interface?

Yes, an interface can extend another interface using the 'extends' keyword. This allows the sub-interface to inherit the methods of the super-interface, and it can also add additional methods of its own.

Follow-up 2

Can a class implement multiple interfaces?

Yes, a class can implement multiple interfaces in Java. This is done by separating the interface names with commas in the 'implements' clause. By implementing multiple interfaces, a class can inherit and provide implementations for all the methods defined in those interfaces.

Follow-up 3

Can you provide an example where both 'extends' and 'implements' are used?

Sure! Here's an example:

public interface Animal {
    void eat();
}

public interface Mammal extends Animal {
    void sleep();
}

public class Dog implements Mammal {
    public void eat() {
        System.out.println("Dog is eating");
    }

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

In this example, the 'Animal' interface defines the 'eat()' method, and the 'Mammal' interface extends the 'Animal' interface and adds the 'sleep()' method. The 'Dog' class implements the 'Mammal' interface, which means it must provide implementations for both the 'eat()' and 'sleep()' methods.

4. What is method overriding in Java?

Method overriding is when a subclass redefines an inherited method with the same signature to provide its own behavior. It powers runtime polymorphism: a call through a superclass/interface reference is dispatched to the actual object's version at runtime (dynamic dispatch).

class Payment { double fee() { return 0; } }
class CardPayment extends Payment {
    @Override double fee() { return amount * 0.029; }   // specialized
}
Payment p = new CardPayment();
p.fee();   // CardPayment's version — chosen by the runtime type

The rules to recite: same name and parameters; return type same or covariant; access not more restrictive; can't add broader checked exceptions; and static/final/private methods can't be overridden. Always use @Override so the compiler catches signature mismatches, and use super.method() to invoke the parent's version.

In the context of inheritance, overriding is the reason inheritance enables polymorphic behavior — the superclass defines a contract/default, and each subclass tailors it, while callers work against the base type. (Distinguish it from overloading, which is same-name/different-parameters resolved at compile time.) A current note: an alternative to overriding-per-subtype is pattern matching for switch over a sealed hierarchy, which centralizes the type-specific logic instead of spreading it across overrides.

↑ Back to top

Follow-up 1

How is it related to inheritance?

Method overriding is closely related to inheritance in Java. When a subclass inherits from a superclass, it also inherits the methods defined in the superclass. By overriding a method in the subclass, we can modify the behavior of the method inherited from the superclass. This allows us to customize the behavior of the subclass while reusing the code from the superclass.

Follow-up 2

What rules must be followed while overriding a method?

When overriding a method in Java, the following rules must be followed:

  1. The method in the subclass must have the same name, return type, and parameters as the method in the superclass.
  2. The access modifier of the method in the subclass must be the same or less restrictive than the access modifier of the method in the superclass.
  3. The subclass method cannot throw a checked exception that is not declared by the superclass method.
  4. The subclass method cannot have a lower visibility than the superclass method.
  5. The subclass method cannot override a final method in the superclass.

Follow-up 3

Can we override a private or static method in Java?

No, we cannot override a private or static method in Java. Private methods are not inherited by subclasses, so there is no concept of overriding them. Static methods are also not overridden in Java, they are hidden. If a subclass defines a static method with the same name as a static method in the superclass, the subclass method will hide the superclass method, but it is not considered as overriding.

5. What is the concept of multiple inheritance?

Multiple inheritance means a class inheriting directly from more than one parent. The key point for Java: Java does NOT allow multiple inheritance of classes — a class can extends only one superclass. This deliberately avoids the "diamond problem": if two superclasses provided different versions of the same method (or conflicting state), the subclass couldn't unambiguously resolve which to inherit.

What Java does allow:

  • Multiple inheritance of type via interfaces — a class can implements many interfaces.
  • Since Java 8, interfaces can have default methods, so you can inherit behavior from multiple interfaces. If two interfaces supply the same default method, the compiler forces you to resolve the conflict explicitly:
interface A { default String hi() { return "A"; } }
interface B { default String hi() { return "B"; } }
class C implements A, B {
    @Override public String hi() { return A.super.hi(); }   // must disambiguate
}

The framing interviewers want: Java supports multiple inheritance of type/behavior (interfaces) but not of state/implementation (classes) — sidestepping the diamond problem while keeping flexibility. To combine implementations from multiple sources, use composition (hold instances and delegate) rather than class inheritance. Mentioning the default-method conflict resolution (A.super.hi()) shows current, precise knowledge.

↑ Back to top

Follow-up 1

Why is multiple inheritance not supported in Java?

Multiple inheritance is not supported in Java because it can lead to several problems and complexities. One of the main issues is the diamond problem, where a class inherits two or more classes that have a common superclass. This can result in ambiguity when calling methods or accessing attributes from the common superclass. To avoid this ambiguity and maintain simplicity, Java only allows single inheritance, where a class can have only one direct superclass.

Follow-up 2

What problems does multiple inheritance introduce?

Multiple inheritance introduces several problems, including:

  1. Diamond Problem: When a class inherits from two or more classes that have a common superclass, it can lead to ambiguity when calling methods or accessing attributes from the common superclass.

  2. Name Clashes: If two parent classes have methods or attributes with the same name, it can cause conflicts and make the code difficult to understand and maintain.

  3. Complexity: Multiple inheritance can make the class hierarchy more complex and harder to understand, especially when dealing with multiple levels of inheritance and multiple parent classes.

Follow-up 3

How can we achieve multiple inheritance in Java?

In Java, multiple inheritance can be achieved using interfaces. An interface is a collection of abstract methods that a class can implement. By implementing multiple interfaces, a class can inherit the abstract methods from each interface, effectively achieving multiple inheritance.

For example:

interface Interface1 {
    void method1();
}

interface Interface2 {
    void method2();
}

class MyClass implements Interface1, Interface2 {
    public void method1() {
        // Implementation
    }

    public void method2() {
        // Implementation
    }
}

Follow-up 4

What is the role of interfaces in achieving multiple inheritance?

Interfaces play a crucial role in achieving multiple inheritance in Java. By implementing multiple interfaces, a class can inherit the abstract methods from each interface, effectively inheriting behaviors from multiple sources.

Interfaces provide a way to define a contract or a set of methods that a class must implement. By implementing multiple interfaces, a class can inherit the behaviors defined in each interface, allowing for code reuse and achieving multiple inheritance.

It's important to note that interfaces only define method signatures and constants, and they cannot contain implementation code. The implementing class is responsible for providing the actual implementation of the methods defined in the interfaces.

Live mock interview

Mock interview: Inheritance

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.