[!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++.