← Back to Chapters

Types of Inheritance in Java

? Types of Inheritance in Java

? Quick Overview

Inheritance in Java allows one class to acquire the properties and behavior of another class. It promotes code reusability, method overriding, and logical class hierarchy.

? Key Concepts

  • Inheritance uses the extends keyword
  • Parent class is also called superclass
  • Child class is also called subclass
  • Java supports multiple inheritance only through interfaces

? Types of Inheritance

  • Single Inheritance
  • Multilevel Inheritance
  • Hierarchical Inheritance
  • Multiple Inheritance (via Interface)
  • Hybrid Inheritance (via Interface)

? Syntax / Theory

A subclass inherits a superclass using the extends keyword.

? View Code Example
// Basic inheritance syntax
class Parent {
void show() {
System.out.println("Parent class method");
}
}

class Child extends Parent {
void display() {
System.out.println("Child class method");
}
}

? Code Example – Single Inheritance

? View Code Example
// Single inheritance example in Java
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}

class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}

class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.eat();
d.bark();
}
}

?️ Live Output / Explanation

Output

Animal is eating
Dog is barking

The Dog class inherits the eat() method from the Animal class.

? Interactive: Visualizing Inheritance

Click the button below to see how the extends keyword unlocks capabilities.

class Vehicle

? startEngine()
? stopEngine()

class Car

? playMusic()
⬇️

Car myCar = new Car();

Methods available to 'myCar':

? playMusic()

? Tips & Best Practices

  • Use inheritance only when a true "is-a" relationship exists
  • Prefer method overriding instead of duplicating code
  • Avoid deep inheritance hierarchies
  • Use interfaces for multiple inheritance

? Try It Yourself

  • Create a multilevel inheritance example
  • Implement hierarchical inheritance using three classes
  • Use an interface to simulate multiple inheritance