Multiple Inheritance in Java is nothing but one class extending more than one class. Java does not have this capability. As the designers considered that multiple inheritance will to be too complex to manage, but indirectly you can achieve Multiple Inheritance in Java using Interfaces.
As in Java we can implement more than one interface we achieve the same effect using interfaces.
Flow Diagram
Conceptually Multiple Inheritance has to be like the below diagram, ClassA and ClassB both inherited by ClassC. Since it is not supported we will changing the ClassA to InterfaceA and ClassB to InterfaceB.
Example of Multiple Inheritance
Here we have two interfaces Car and Bus.
- Car interface has a attribute speed and a method defined distanceTravelled()
- Bus interface has a attribute distance and method speed()
The Vehicle class implements both interface Car and Bus and provides implementation.
package com.javainterviewpoint.inheritance; interface Car { int speed=60; public void distanceTravelled(); } interface Bus { int distance=100; public void speed(); } public class Vehicle implements Car,Bus { int distanceTravelled; int averageSpeed; public void distanceTravelled() { distanceTravelled=speed*distance; System.out.println("Total Distance Travelled is : "+distanceTravelled); } public void speed() { int averageSpeed=distanceTravelled/speed; System.out.println("Average Speed maintained is : "+averageSpeed); } public static void main(String args[]) { Vehicle v1=new Vehicle(); v1.distanceTravelled(); v1.speed(); } }
Output :
Total Distance Travelled is : 6000 Average Speed maintained is : 100
In the above code we doesn’t have ambiguity even when we use classes instead of interfaces, then there comes the question why Java is not supporting ?. The problem arises when both the classes has the same method in it ? and the compiler will not know which method to call whereas the methods of the interfaces are by default abstract and implementations are not provided by the interface and hence we can avoid the ambiguity.
package com.javainterviewpoint.inheritance; interface InterfaceA { public void disp(); } interface InterfaceB { public void disp(); } public class Client implements InterfaceA,InterfaceB { @Override public void disp() { System.out.println("disp() method implementation"); } public static void main(String args[]) { Client c = new Client(); c.disp(); } }
Output :
disp() method implementation
As we can see in the above code the Client class has implemented both the interfaces InterfaceA and InterfaceB. In this case we didn’t have ambiguity even though both the interfaces are having same method.
Neha says
This is a wonderful site.I found it very helpful. Keep going!!!!
Deepa says
Your website is more useful for beginners in java thnks for uploading information