Inheritance allows one class to acquire the properties and methods of another class using
extends.It establishes an IS-A relationship, letting you reuse common code instead of rewriting it from scratch.
Type | Structure | Example |
|---|---|---|
Single | One child class extends one parent class. |
|
Multilevel | A chain of inheritance of more than 2 classes. |
|
Hierarchical | Multiple child classes inherit from the same parent class. |
|
Multiple (Interfaces) | Java does not support multiple inheritance, but it supports multiple inheritance through interfaces. |
|
Hybrid (Interfaces) | A mix of class inheritance and multiple interfaces. |
|
Ex: Family Traits (Biological Inheritance)
Parent -> Child: Just as a child naturally inherits traits like eye color or height from their parents while developing their own distinct personality and skills, a Java subclass inherits existing attributes and behaviors from its superclass while adding its own methods.
# Parent class (Superclass)
class Vehicle {
String brand = "Tata";
void startEngine() {
System.out.println("Engine started.");
}
}
# Child class (Subclass) inherits from Vehicle
class Car extends Vehicle {
int doors = 4;
void honk() {
System.out.println(brand + " car honks: Beep beep!");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.startEngine(); # Inherited from Vehicle
myCar.honk(); # Defined in Car
System.out.println("Doors: " + myCar.doors);
}
}