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 {}
2οΈβ£ Multilevel Inheritance
Grandparent β Parent β Child
class A {}
class B extends A {}
class C extends B {}
Example:
class Vehicle {
void start() {
System.out.println("Vehicle is starting");
}
}
class Car extends Vehicle {
void wheels() {
System.out.println("Car has 4 wheels");
}
}
class Tesla extends Car {
void autopilot() {
System.out.println("Tesla has autopilot feature");
}
}
public class Main {
public static void main(String[] args) {
Tesla t = new Tesla();
t.start(); // From Vehicle
t.wheels(); // From Car
t.autopilot(); // From Tesla
}
}
3οΈβ£ Hierarchical Inheritance
One parent β Multiple children
class A {}
class B extends A {}
class C extends A {}
Example:
class Bank {
void deposit() {
System.out.println("Money deposited");
}
void withdraw() {
System.out.println("Money withdrawn");
}
}
class SavingsAccount extends Bank {
void interest() {
System.out.println("Savings Account earns interest");
}
}
class CurrentAccount extends Bank {
void overdraft() {
System.out.println("Current Account has overdraft facility");
}
}
public class Main {
public static void main(String[] args) {
SavingsAccount s = new SavingsAccount();
s.deposit(); // From Bank
s.interest(); // From SavingsAccount
CurrentAccount c = new CurrentAccount();
c.withdraw(); // From Bank
c.overdraft(); // From CurrentAccount
}
}
4οΈβ£ Multiple Inheritance
Java does NOT allow this with classes because of ambiguity (Diamond Problem).
β Java supports multiple inheritance using interfaces.
β 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)