0
0
Javaprogramming~5 mins

Multiple inheritance using interfaces in Java

Choose your learning style9 modes available
Introduction

Multiple inheritance lets a class use features from more than one source. Java uses interfaces to do this safely.

When a class needs to follow rules from different sources.
When you want to share method ideas without sharing code.
When you want to build flexible and reusable code parts.
When you want to avoid problems that come with multiple class inheritance.
Syntax
Java
interface Interface1 {
    void method1();
}

interface Interface2 {
    void method2();
}

class MyClass implements Interface1, Interface2 {
    public void method1() {
        // code here
    }
    public void method2() {
        // code here
    }
}

A class can implement many interfaces separated by commas.

All interface methods must be implemented in the class.

Examples
This class Duck can both fly and swim by implementing two interfaces.
Java
interface Flyable {
    void fly();
}

interface Swimmable {
    void swim();
}

class Duck implements Flyable, Swimmable {
    public void fly() {
        System.out.println("Duck is flying");
    }
    public void swim() {
        System.out.println("Duck is swimming");
    }
}
Document class implements two interfaces to print and show content.
Java
interface Printable {
    void print();
}

interface Showable {
    void show();
}

class Document implements Printable, Showable {
    public void print() {
        System.out.println("Printing document");
    }
    public void show() {
        System.out.println("Showing document");
    }
}
Sample Program

This program shows a Robot class using two interfaces to speak and move.

Java
interface Speaker {
    void speak();
}

interface Mover {
    void move();
}

class Robot implements Speaker, Mover {
    public void speak() {
        System.out.println("Robot says: Hello!");
    }
    public void move() {
        System.out.println("Robot is moving forward");
    }
}

public class Main {
    public static void main(String[] args) {
        Robot r = new Robot();
        r.speak();
        r.move();
    }
}
OutputSuccess
Important Notes

Interfaces only have method declarations, no code inside methods (except default methods in newer Java).

Multiple inheritance with classes is not allowed in Java to avoid confusion, but interfaces solve this.

Use interfaces to design flexible and clear contracts for classes.

Summary

Java uses interfaces to allow multiple inheritance safely.

A class can implement many interfaces and must define their methods.

This helps build flexible and reusable code parts.