Inheritance in OOP — The Principle Explained
Inheritance lets you create a new class that inherits fields and methods from an existing class. The new class can add its own features or modify inherited ones.
The Analogy
A smartphone inherits everything a basic phone does (calls, contacts) and adds new features (apps, camera, GPS). You don’t rebuild the calling functionality — you inherit it.
The IS-A Relationship
Inheritance models an IS-A relationship:
- A Dog IS-A Animal
- A Manager IS-A Employee
- A Circle IS-A Shape
Animal
/ \
Dog Cat
class Animal {
String name;
void eat() { System.out.println(name + " is eating"); }
}
class Dog extends Animal {
void bark() { System.out.println(name + " says Woof!"); }
}
Dog d = new Dog();
d.name = "Buddy";
d.eat(); // inherited from Animal
d.bark(); // Dog's own method
Terminology
| Term | Meaning |
|---|---|
| Parent / Superclass / Base class | The class being inherited from |
| Child / Subclass / Derived class | The class that inherits |
extends |
Java keyword for inheritance |
super |
Reference to the parent class |
Why Inheritance Matters
- Code reuse — don’t repeat common logic
- Hierarchy — model real-world relationships
- Polymorphism — treat different objects uniformly (covered next)
- Extensibility — add new types without changing existing code
Inheritance Anti-Pattern
Don’t use inheritance just to reuse code. Use it only when there’s a genuine IS-A relationship.
// BAD — a Stack is NOT an ArrayList
class Stack extends ArrayList { }
// GOOD — a Stack HAS-A list (composition)
class Stack {
private List<Object> items = new ArrayList<>();
}
Summary
- Inheritance = child class inherits from parent class
- Models IS-A relationships
- Enables code reuse and polymorphism
- Prefer composition over inheritance when there’s no IS-A relationship
→ Full implementation in the Inheritance Deep Dive chapters.
What’s Next?
Next principle: Polymorphism — one interface, many implementations.