👨👦 What is Inheritance?
Inheritance is the mechanism in Object-Oriented Programming where one class (child/subclass) derives (or inherits) properties and behavior (methods) from another class (parent/superclass).
It’s like saying:
“A child class gets all the traits of its parent class.”
This promotes code reuse because you don’t need to rewrite common functionality — you define it once in the parent, and all children automatically get it.
🔗 Inheritance Example
Parent class (superclass)
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
Child class (subclass)
class Dog extends Animal { // 'extends' means Dog inherits from Animal
void bark() {
System.out.println("Woof Woof");
}
}
Using Inheritance
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // inherited from Animal
dog.bark(); // defined in Dog
}
}
✅ Dog can eat() even though eat() was never written in Dog — it inherited it from Animal.
💡 Types of Inheritance (in Java)
| Type | Example |
|---|---|
| Single Inheritance | One class inherits from one class (like Dog inherits Animal). |
| Multilevel Inheritance | Class A → Class B → Class C (a chain). |
| Hierarchical Inheritance | One parent class, multiple child classes. |
| Multiple Inheritance (via Interfaces) | Java doesn’t support multiple inheritance with classes (to avoid conflicts), but it supports it with interfaces. |
🚀 Benefits of Inheritance
✅ Reuse code instead of duplicating it.
✅ Follow the “is-a” relationship — a Dog is an Animal, a Car is a Vehicle.
✅ Makes the code easier to maintain and extend.
⚠️ Inheritance Gotchas
- If not used carefully, it can lead to tight coupling (child depends too much on parent).
- Favor Composition over Inheritance if a class doesn’t truly follow “is-a” logic.