Java multiple Inheritance: Interfaces and Composition

Inheritance means a class extending other class. Multiple Inheritance means single class extending more than one class. Java does not support this kind of inheritance as one class can inherit only a single class.

Q. Why Java does not support multiple inheritance?

Consider a scenario, there are 2 classes

class A{

public void mymethod(){//some code

}

}

class B{

public void mymethod(){//some code

}

}

class C extends A,B{//illegal in Java

//which implementation of mymethod is imported ?

}

If java allow multiple inheritance, it will be tricky to handle above situation with multiple inheritance, hence Java does not allow it.

Q. How does Java implement Multiple inheritance?

Java does not provide direct implementation of multiple inheritance by extending more than one classes, but it provides you 2 alternatives.

1. Use of Interfaces: A Java class cannot extend more than one class, but it can implement any number of interfaces.

Class C implements A,B{ // this time A and B are interface

public void mymethod(){//interfaces did not provide implementation and hence no conflict

}

}

2. Composition: Other way to use properties of other classes is to use composition, that is have the object of other classes as part of current class.

Class C{//A and B are different classes

A objA=new A();

B objB=new B();

}

Best Approach: A mix of implementing interfaces, extending class and using composition, based on different requirements