Multiple Inheritance in Java

Learn multiple inheritance in java using interface with example programs – Multiple inheritance  can be implemented using interfaces not classes.

Note that java does not support multiple inheritance using classes. But, we can achieve it using interfaces.

In other words, in Java, a class can extend only one class but can implement multiple interfaces. Recommended to read the following topics before moving further: Java inheritance concept with simple example.

Multiple inheritance in Java using interface

Below is very simple java program. In this java program, Bird class will extend one class (Color) and achieve multiple inheritance behavior by implementing two interfaces i.e. IFlyable and IEatable .

/*----------------------------------------
 * Multiple Inheritance using interface example program
 */

//Color class will be extended by derived class
//Bird
class Color {
	public void red() {

		System.out.println("Green...");
	}
}

/*----------------------------------------
 * Two Inheritances that Bird class will implement 
 */

interface IFlyable {
	void fly();
}

interface IEatable {
	void eat();
}

// Bird class will implement interfaces and extend Color class
class Bird extends Color implements IFlyable, IEatable {
	// Implement method of interfaces
	public void fly() {
		System.out.println("Bird flying");
	}

	public void eat() {
		System.out.println("Bird eats");
	}
	// It can have more own methods.
}

/*----------------------------------------
 * Test program  - multiple inheritance using interface
 */
public class MultipleInheritanceJava {

	public static void main(String[] args) {

		Bird b = new Bird();
		// Call methods implemented by Bird class
		// from two interfaces
		b.eat();
		b.fly();
		// call method inherited from Color class
		b.red();

	}

}

Output:

Bird eats Bird flying Green…



Leave a Comment