Back to Study Material Java

Inheritance in Java

Inheritance is the mechanism by which one class acquires the fields and methods of another. In Java, a class inherits from a parent (superclass) using the ...

Inheritance in Java

Extending Classes to Reuse and Specialize Behavior

Inheritance is the mechanism by which one class acquires the fields and methods of another. In Java, a class inherits from a parent (superclass) using the extends keyword. The child class (subclass) gets all non-private members of the parent and can add new fields, new methods, or provide its own implementations of existing methods. This promotes code reuse and establishes an "is-a" relationship: a Truck is a Vehicle, so Truck can extend Vehicle.

Single vs Multiple Inheritance Java supports only single class inheritance: a class can extend exactly one other class. This avoids the "diamond problem" that arises in languages that allow multiple class inheritance, where two parent classes have conflicting implementations of the same method. Java achieves some of the benefits of multiple inheritance through interfaces, where a class can implement any number of interfaces. Since Java 8, interfaces can also provide default method implementations.

The Object Class at the Root Every class in Java implicitly extends java.lang.Object if it does not explicitly extend anything else. This means every Java object inherits Object's methods: equals(), hashCode(), toString(), getClass(), wait(), notify(), and notifyAll(). Overriding equals() and hashCode() consistently is critical for objects used in collections. toString() should be overridden to provide a human-readable description for logging and debugging.

Constructor Behavior in Inheritance Constructors are not inherited, but the first thing any constructor must do is call a constructor in its parent class. If you do not write an explicit super() call, Java inserts super() automatically. If the parent has no no-argument constructor, you must explicitly call super(arg1, arg2) with matching arguments. The chain continues up to Object, ensuring full initialization from root to leaf before any code in the child constructor runs.

Code Example: class Animal { String name; Animal(String name) { this.name = name; } void speak() { System.out.println(name + " makes a sound."); } }

class Dog extends Animal { Dog(String name) { super(name); } @Override void speak() { System.out.println(name + " barks."); } }

Animal a = new Dog("Rex"); a.speak(); // Rex barks.

Interview Tip: Interviewers love to ask why Java chose single inheritance for classes. The clear answer is to avoid ambiguity: if class C extends both A and B, and both A and B have a method doWork(), the JVM cannot know which to use without a complex conflict-resolution rule. Java sidesteps this entirely by limiting class inheritance to one parent while allowing multiple interface implementation.