Types of inheritances in java

In Java, there are four types of inheritance:

  1. Single Inheritance: A class can only inherit from one superclass. This is the simplest and most common form of inheritance.
  2. Multilevel Inheritance: A class can inherit from a superclass, which in turn can inherit from another superclass. This creates a hierarchy of classes.
  3. Hierarchical Inheritance: Several subclasses inherit from the same superclass. This means that the superclass is the parent of multiple child classes.
  4. Multiple Inheritance: A class can inherit from multiple superclasses. However, Java does not support multiple inheritance directly, because it can lead to ambiguity and other problems. Instead, Java uses interfaces to achieve some of the benefits of multiple inheritance while avoiding the issues.

Here’s an example to illustrate each type of inheritance:

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

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

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

class Mammal extends Animal {
  void breathe() {
    System.out.println("Breathing...");
  }
}

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

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

class Cat extends Animal {
  void meow() {
    System.out.println("Meowing...");
  }
}

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

// Multiple Inheritance (with interface)
interface A {
  void a();
}

interface B {
  void b();
}

class C implements A, B {
  public void a() {
    System.out.println("A...");
  }

  public void b() {
    System.out.println("B...");
  }
}

In this example, the Dog class is used to demonstrate single inheritance, the Dog class with Mammal class is used to demonstrate multilevel inheritance, the Dog and Cat classes are used to demonstrate hierarchical inheritance, and the C class with interfaces A and B is used to demonstrate multiple inheritance.

Share