Multiple Inheritance with Interfaces

Java supports multiple inheritance through interfaces, allowing a class to implement multiple interfaces and inherit abstract methods from each of them.

Creating Multiple Interfaces:

Let's start by creating two interfaces, each with its own set of abstract methods.


// First interface
public interface Walkable {
  void walk();
}

// Second interface
public interface Swimmable {
  void swim();
}

Implementing Multiple Interfaces:

Now, let's create a class that implements both interfaces. The class will inherit abstract methods from both interfaces.


// Class implementing multiple interfaces
public class Human implements Walkable, Swimmable {

  // Implementing walk method
  public void walk() {
    System.out.println("Human is walking.");
  }

  // Implementing swim method
  public void swim() {
    System.out.println("Human is swimming.");
  }

}

Using the Implemented Class:

Now, let's create an instance of the Human class and use the inherited methods from both interfaces.


// Main class
public class Main {

  // Main method
  public static void main(String[] args) {
    // Creating an instance of Human
    Human human = new Human();

    // Using methods from both interfaces
    human.walk();
    human.swim();
  }

}

Note:

Java supports multiple inheritance through interfaces, allowing classes to implement multiple interfaces and inherit abstract methods from each interface. This provides a flexible way to achieve polymorphism and code reuse.