[!NOTE] The second pillar of Object-Oriented Programming is Inheritance. It allows a new class to drastically cut down on duplicate code by inheriting all the attributes and methods of an existing class.
The 'extends' Keyword
Imagine you are building a Zoo application. You need a Lion class, a Penguin class, and a Monkey class.
All of them need health, age, and a eat() method. Writing those three variables in every single class is a violation of the DRY (Don't Repeat Yourself) principle.
Instead, we create a generic Parent class (Superclass), and have the Children classes (Subclasses) inherit from it using the extends keyword.
// 1. The Superclass
public class Animal {
protected int health = 100; // 'protected' means children can see this, but the public cannot.
public void eat() {
System.out.println("The animal consumes food.");
}
}
// 2. The Subclass
// A Lion *is an* Animal. It gets everything Animal has automatically!
public class Lion extends Animal {
// Unique to the Lion!
public void roar() {
System.out.println("ROAARRR!");
}
}
public class Main {
public static void main(String[] args) {
Lion simba = new Lion();
simba.eat(); // Inherited from Animal! Output: "The animal consumes food."
simba.roar(); // Specific to Lion.
System.out.println(simba.health); // Output: 100
}
}
The 'super' Keyword
What if the Parent Class has a Constructor that requires parameters? The Child class must successfully build the Parent portion of itself before it can exist.
To achieve this, the first line of a child's constructor must use the super() keyword to pass data up to the parent.
public class Employee {
String name;
// Parent Constructor requires a Name
public Employee(String name) {
this.name = name;
}
}
public class Manager extends Employee {
int teamSize;
public Manager(String name, int teamSize) {
// 1. Call the Parent Constructor and pass the required name
super(name);
// 2. Initialize the child's specific fields
this.teamSize = teamSize;
}
}
[!CAUTION] Single Inheritance Only: A Child class can only have one direct Superclass in Java. You can say
class Lion extends Animal, but you CANNOT sayclass Lion extends Animal, Predator. This restriction prevents catastrophic ambiguity (the "Diamond Problem") common in C++.
Use Inheritance for True Is-A Relationships
Inheritance works best when the child really is a specialized version of the parent. A Manager is an Employee. A Car is a Vehicle. But a Report is not a Printer; it may simply use a printer.
Inheritance vs Composition
// Inheritance: ElectricCar is a Vehicle
class ElectricCar extends Vehicle {
}
// Composition: Order has a PaymentService
class OrderService {
private PaymentService paymentService;
}
Use composition when a class needs help from another object. Use inheritance when the child should be usable wherever the parent is expected.
Overriding Parent Behavior
class Employee {
double calculateBonus() {
return 1000;
}
}
class Manager extends Employee {
@Override
double calculateBonus() {
return 3000;
}
}
Common Mistakes
- Using inheritance only to reuse code when composition would be clearer.
- Making parent fields
protectedtoo quickly instead of using methods. - Forgetting that Java classes support only one direct parent class.
- Creating very deep inheritance chains that are hard to reason about.
Mini Practice
Create an Employee class and two child classes: Developer and Designer. Give each child a different implementation of getRoleDescription().
Practice Lab: Employee Hierarchy
Use inheritance only where the relationship is truly is-a.
- Create a parent class
Employeewith name and base salary. - Add a method
calculateMonthlyPay(). - Create
DeveloperandManagerchild classes. - Override pay calculation or role description where needed.
- Use
superto initialize parent fields.
Goal: Practice inheritance, extends, super, and child-specific behavior.
Revision Checkpoint
extends: Creates a parent-child class relationship.- Is-a test: Use inheritance when the child truly is a parent type.
super(...): Calls the parent constructor.- Single inheritance: A class can extend only one direct parent class.
- Composition: Prefer has-a relationships when a class only uses another object.
Before the quiz: Decide whether each relationship is inheritance or composition.