π³ Inheritance in Java β Reusing Code Like a Pro!
In Object-Oriented Programming (OOP), Inheritance is like a family tree π¨βπ©βπ§βπ¦ β where child classes inherit qualities from their parent class.
π What is Inheritance?
π Inheritance is the mechanism in Java where one class (child/subclass) acquires the properties and behaviors (fields & methods) of another class (parent/superclass).
It helps in code reusability and establishes a natural hierarchy between classes.
π‘ Real-World Analogy
Think about a Car π:
-
A general Car (parent class) has properties like speed, fuel, wheels.
-
A SportsCar (child class) inherits all of these, but can also add its own features like turbo boost.
So, the child doesnβt need to redefine everything β it just reuses and adds more!
Terms used in Inheritance:
- Class:Β A class is a group of objects which have common properties. It is a template or blueprint from which objects are created.
- Sub Class/Child Class:Β Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class.
- Super Class/Parent Class:Β Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class.
- Reusability:Β As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class.
β‘ Types of Inheritance in Java
πΉ Single Inheritance β One class inherits from another.
πΉ Multilevel Inheritance β A class inherits from a class which inherits from another.
πΉ Hierarchical Inheritance β Multiple classes inherit from one parent.
β Multiple Inheritance (two classes as parents) is not supported directly in Java (to avoid ambiguity), but achieved via interfaces.
π₯οΈ Java Example: Inheritance in Action
// Parent class
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
// Child class
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
// Main class
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.eat(); // Inherited from Animal
d.bark(); // Defined in Dog
}
}
β Output:
This animal eats food.
The dog barks.
π― Benefits of Inheritance
-
π Code Reusability β Write once, reuse everywhere.
-
π Extensibility β Add new features without touching existing code.
-
π§© Organization β Creates a clear class hierarchy.
-
π Faster Development β Less code duplication = faster coding.
β¨ Quick Summary
π Inheritance = Parent β Child relationship in OOP.
The child class inherits methods & variables from the parent, making code cleaner, shorter, and more powerful.
π‘ Pro Tip: Always use inheritance when there is an βis-aβ relationship.
Example: Dog is an Animal β
| Car is a Vehicle β
| Keyboard is a Computer β (wrong, thatβs composition).
Β