Multiple inheritance
In multiple inheritance, sub classes are derived from multiple super classes.
If two super classes are same names for their variables or methods, then which member is inherited to the subclass is the issue in multiple inheritance.
Multiple inheritance in Java using interfaces
Java doesn’t support multiple inheritance with classes. So, a subclass cannot extend more than one super classes.
However, in java, one class can implement more than one interface.
In below example, we have two interfaces One and Two that have same member variable and method.
public interface One { int num = 10; void method(); } public interface Two { int num = 20; void method(); }
Since, the interfaces don’t define any method implementation, the implementing class will provide the method implementation.
Hence, there is no confusion on which behaviour the class receives.
The variables defined in the interfaces are constants that can be access using the Class name; i.e. One.num or Two.num
Here is the code for an implementing class for these interfaces :
public class ClassOneTwo implements One, Two { public void method() { System.out.println("Sum is " + One.num+Two.num); } }
In the above code, ClassOneTwo implements both the interfaces One and Two.
It accesses the interface variable as One.num and Two.num respectively.. so, there is not confusion regarding accessing variable.
Since, the interfaces just provided method signature, ClassOneTwo provides the signature as per its own need.
© 2015, https:. All rights reserved. On republishing this post, you must provide link to original post