DEV Community

Murali Rajendran
Murali Rajendran

Posted on

🧬 Types of Inheritance in Java

Inheritance in Java allows one class to acquire properties and behaviors (fields and methods) of another class. It promotes code reusability and method overriding.

Types:
1.1. Single Inheritance

A subclass inherits from one superclass.

class Animal {
void eat() { System.out.println("Eating..."); }
}

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

2.2. Multilevel Inheritance

A chain of inheritance.

// Parent class
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

// Child class
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}

// Child class
class Cat extends Animal {
void sound() {
System.out.println("Cat meows");
}
}

// Child class
class Cow extends Animal {
void sound() {
System.out.println("Cow moos");
}
}

// Main class
public class Geeks {
public static void main(String[] args) {
Animal a;
a = new Dog();
a.sound();

    a = new Cat();
    a.sound(); 

    a = new Cow();
    a.sound();  
}
Enter fullscreen mode Exit fullscreen mode

}

3.3. Hierarchical Inheritance

  1. Multiple subclasses inherit from one superclass.
  2. In hierarchical inheritance, more than one subclass is inherited from a single base class. i.e. more than one derived class is created from a single base class.

class Vehicle {
Vehicle() {
System.out.println("This is a Vehicle");
}
}

class Car extends Vehicle {
Car() {
System.out.println("This Vehicle is Car");
}
}

class Bus extends Vehicle {
Bus() {
System.out.println("This Vehicle is Bus");
}
}

public class Test {
public static void main(String[] args) {
Car obj1 = new Car();
Bus obj2 = new Bus();
}
}

4.Multiple Inheritance (via Interface)

  1. Java doesn’t support multiple inheritance with classes — to avoid ambiguity —
  2. The interfaces allow it.
  3. The Java does not support multiple inheritances with classes. In Java, we can achieve multiple inheritances only through Interfaces.

interface A { void show(); }
interface B { void display(); }

class C implements A, B {
public voiIt is a mix of two or more of the above types of inheritance. In Java, we can achieve hybrid inheritance only through Interfaces d show() { System.out.println("Show"); }
public void display() { System.out.println("Display"); }
}

5.Hybrid Inheritance

  1. Combination of more than one type (e.g., multiple + multilevel).
  2. Achieved using interfaces only..
  3. It is a mix of two or more of the above types of inheritance. In Java, we can achieve hybrid inheritance only through Interfaces

Type Example Supported by
Single A → B Classes
Multilevel A → B → C Classes
Hierarchical A → B, A → C Classes
Multiple A, B → C Interfaces
Hybrid Combination Interfaces

Top comments (0)