Inheritance
TL;DR
- Inheritance allows a new class (child/subclass) to inherit the fields and methods of an existing class (parent/superclass).
- It establishes an IS-A relationship (e.g., a Dog IS-A Animal).
- It promotes code reusability and enables Polymorphism.
- Uses the
extendskeyword in Java.
Concept
When multiple classes share common characteristics, you can extract those commonalities into a parent class. The child classes then inherit everything from the parent, preventing you from writing the same code multiple times.
Key Rules in Java
- Single Inheritance: A class in Java can only
extendone parent class. (Multiple inheritance is not allowed for classes to avoid the “Diamond Problem”). ObjectSuperclass: Every single class in Java implicitly inherits from thejava.lang.Objectclass.- Private Members: Child classes do not inherit
privatefields or methods from the parent. (They can access them indirectly via public getters/setters).
Examples
// Parent Class (Superclass)
class Animal {
String species = "Animal";
public void eat() {
System.out.println("This animal is eating.");
}
}
// Child Class (Subclass) inherits from Animal
class Dog extends Animal {
public void bark() {
System.out.println("Woof!");
}
}
public class InheritanceExample {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // Inherited method!
myDog.bark(); // Its own method
System.out.println(myDog.species); // Inherited field
}
}
Interview Questions
Q: Why does Java not support multiple inheritance of classes?
A: Java avoids multiple inheritance to prevent ambiguity, specifically the Diamond Problem. If Class C inherits from Class A and Class B, and both A and B define a method start(), the compiler wouldn’t know which start() method Class C should inherit. Java solves this by allowing a class to implement multiple Interfaces instead of extending multiple classes.
Q: Do child classes inherit constructors from the parent class?
A: No. Constructors are never inherited. However, the constructor of the child class must invoke the constructor of the parent class (using super()) as its very first statement. If you don’t write super(), the Java compiler automatically inserts a call to the parent’s no-argument constructor super();.