Inheritance
Overview
Inheritance is the OOP mechanism that allows a new class (the Child/Subclass) to absorb the attributes and methods of an existing class (the Parent/Superclass). It heavily promotes code reusability and establishes a hierarchical relationship.
For example, instead of writing separate Dog, Cat, and Bird classes that all duplicate the eat() and sleep() methods, you create a parent Animal class. The subclasses use the extends keyword to instantly inherit those behaviors, allowing them to focus entirely on their unique traits (like bark() for Dog, or fly() for Bird).
Java enforces Single Inheritance for classes. A child class can only extend exactly ONE parent class, preventing the notorious 'Diamond Problem' found in C++ where a child inherits conflicting methods from multiple parents.
Syntax
// The Parent Class (Superclass)
public class Animal {
String name;
public void eat() {
System.out.println(name + " is eating.");
}
}
// The Child Class (Subclass)
// 'extends' grants the Dog all of Animal's non-private members
public class Dog extends Animal {
public void bark() {
System.out.println("Woof!");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.name = "Rex"; // Inherited attribute!
myDog.eat(); // Inherited method!
myDog.bark(); // Unique child method!
}
}Common Pitfalls
- Attempting Multiple Inheritance. Writing
class Child extends Father, Motherwill cause an instant compilation error. Java classes can only have one direct parent. - Assuming
privatefields are inherited. A child class does NOT inherit variables or methods marked asprivatein the parent class. If you want the child to access them but keep them hidden from the outside world, you must use theprotectedaccess modifier.
Interview Questions
Yes! If you do not explicitly use the extends keyword, Java implicitly injects extends Object. The java.lang.Object class is the ultimate root parent of every single class in Java, granting universal methods like .toString() and .equals().
Inheritance establishes an 'IS-A' relationship. Because a Dog extends Animal, a Dog IS-A(n) Animal. This is a critical concept for Polymorphism, allowing you to store a Dog object inside an Animal reference variable.
Real-World Example
UI frameworks (like Android or JavaFX) rely heavily on Inheritance. They provide a generic View class that handles core logic like width, height, and margins. Developers then create specific elements like Button extends View and TextView extends View.
public class Button extends View {
// Inherits setWidth(), setHeight(), and isVisible from View
// Only handles Button specific logic
public void setOnClickListener(Action a) { ... }
}Check Your Knowledge
Test your understanding of Inheritance with these quick questions.