DEV Community

Kesavarthini
Kesavarthini

Posted on

Inheritance in Java

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
    }
}
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ 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 {}
Enter fullscreen mode Exit fullscreen mode

βœ… 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)