Inheritance allows a new class to acquire members (attributes and methods) from an existing class, establishing an IS-A relationship.
public class Animal {
protected String name;
public void eat() {
System.out.println("Eating food");
}
}
public class Dog extends Animal {
public void bark() {
System.out.println("Woof!");
}
}
Generalization and Specialization
Generalization: Moving upward in the hierarchy from specific subclasses toward a common superclass (e.g. Dog→Animal).
Specialization: Moving downward into specialized behavior and state (e.g. Animal→Dog).
Important Design Guideline
"Favor object composition over class inheritance where appropriate."
Inheritance introduces high coupling between the superclass and subclass. Reusability does not always mandate inheritance—composition and delegation frequently yield more flexible architectures.
Exercise 1
Question
Can a Java class extend more than one superclass directly?
Show solution ↓Hide solution ↑
Solution
No. Java enforces single inheritance for classes to prevent ambiguities like the diamond problem. Multiple behavior contracts are achieved through interfaces.