Inheritance in OOP π§¬
What is Inheritance? π€
Inheritance is an OOP principle that allows a class (child/subclass) to derive properties and behaviors from another class (parent/superclass). It promotes code reusability and establishes a hierarchy between classes.
Real-Life Example π:
Think of a family tree π¨βπ©βπ¦. A child inherits traits like eye color or height from their parents, just like a class inherits attributes and methods from another class.
Types of Inheritance π
1οΈβ£ Single Inheritance β‘οΈ
One class inherits from another.
Example π:
class Animal {
void makeSound() {
System.out.println("Some generic animal sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Woof! Woof!");
}
}
2οΈβ£ Multilevel Inheritance β«
A class inherits from a class that is already inherited from another class.
Example π:
class Animal {
void eat() { System.out.println("Eating..."); }
}
class Mammal extends Animal {
void breathe() { System.out.println("Breathing..."); }
}
class Dog extends Mammal {
void bark() { System.out.println("Barking..."); }
}
3οΈβ£ Hierarchical Inheritance π³
One parent class is inherited by multiple child classes.
Example π:
class Animal {
void makeSound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Bark!");
}
}
class Cat extends Animal {
void meow() {
System.out.println("Meow!");
}
}
4οΈβ£ Multiple Inheritance (via Interfaces) π
Java does not support multiple inheritance directly but allows it using interfaces.
Example π:
interface Engine {
void start();
}
interface Transmission {
void shiftGears();
}
class Car implements Engine, Transmission {
public void start() {
System.out.println("Car engine starting...");
}
public void shiftGears() {
System.out.println("Car shifting gears...");
}
}
5οΈβ£ Hybrid Inheritance ποΈ
A mix of multiple inheritance types (achieved via interfaces in Java).
super
Keyword π
The super
keyword is used to call the parent class constructor or access parent methods.
Example π:
class Animal {
String name = "Animal";
}
class Dog extends Animal {
String name = "Dog";
void printName() {
System.out.println("Parent: " + super.name);
System.out.println("Child: " + this.name);
}
}
Why Use Inheritance? π€
β
Code Reusability: Avoids code duplication.
β
Hierarchy Representation: Establishes relationships between classes.
β
Scalability: New features can be added without modifying existing code.
Conclusion π―
Inheritance is a powerful OOP concept that enhances code reusability and organization. It helps build flexible and scalable software applications! π
π¬ Which type of inheritance have you used in your projects? Share your thoughts below!
Subscribe to my newsletter
Read articles from ππ¬π³π¦π°π₯ ππ¬πΆππ© directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
