What is Inheritance?
Inheritance in Java is a feature where one class (child) can use the properties and methods of another class (parent).
- The class that is inherited from is called Parent / Superclass
- The class that inherits is called Child / Subclass
- Java uses the keyword extends to achieve inheritance.
In short
- Parent class β Superclass
- Child class β Subclass
- Keyword used β extends
π§ Real-World Idea
Think like this
- A Car is a Vehicle
- A Dog is an Animal
- A Student is a Person
This βIS-Aβ relationship is exactly what inheritance represents.
π» Simple Code Example
class Vehicle {
void start() {
System.out.println("Vehicle is starting");
}
}
class Car extends Vehicle {
void drive() {
System.out.println("Car is driving");
}
public static void main(String[] args) {
Car c = new Car();
c.start(); // inherited
c.drive(); // own method
}
}
π Why Do We Need Inheritance?
- Code reusability
- Reduces duplicate code
- Improves maintainability
- Supports method overriding
- Helps achieve runtime polymorphism
π Types of Inheritance
1οΈβ£ Single Inheritance
One child β One parent
class A {}
class B extends A {}
β Advantages of Inheritance
- Code reusability
- Less duplication
- Easy maintenance
- Supports polymorphism
- Clean structure
β Disadvantages of Inheritance
- Tight coupling
- Parent changes affect child
- Complex hierarchy
- Not always flexible

Top comments (0)