Multiple inheritance is the capability of creating a single class with multiple superclasses.Unlike some other popular object oriented programming languages like C++, java doesn’t provide support for multiple inheritance in classes.Java doesn’t support multiple inheritance in classes because it can lead to diamond problem .
Diamond Problem
In that case, we could have
a class hierarchy like below image.
Base Class
public abstract class SuperClass {
public abstract void doSomething();
}
CLASS A
public class ClassA extends SuperClass{
@Override
public void doSomething(){
System.out.println("doSomething
implementation of A");
}
//ClassA
own method
public void methodA(){
}
}
CLASS B
public class ClassB extends SuperClass{
@Override
public void doSomething(){
System.out.println("doSomething
implementation of B");
}
//ClassB
specific method
public void methodB(){
}
}
CLASS C
public class ClassC extends ClassA, ClassB{
public void test(){
//calling
super class method
doSomething();
}
}
test()
method is making a call to
superclass doSomething()
method, this leads to the
ambiguity as compiler doesn’t know which superclass method to execute and
because of the diamond shaped class diagram, it’s referred as Diamond Problem
and this is the main reason java doesn’t support multiple inheritance in
classes.
Multiple Inheritance in Interfaces
multiple inheritance is not supported in classes but it’s
supported in interfaces and a single interface can extend multiple interfaces,
below is a simple example.
public interface InterfaceA {
public void doSomething();
}
public interface InterfaceB {
public void doSomething();
}
Notice that both the interfaces are declaring same method,
now we can have an interface extending both these interfaces like below.
public interface InterfaceC extends InterfaceA, InterfaceB
{
//same
method is declared in InterfaceA and InterfaceB both
public void doSomething();
}
This is perfectly fine because the interfaces are only
declaring the methods and the actual implementation will be done by concrete
classes implementing the interfaces, so there is no possibility of any kind of ambiguity
in multiple inheritance in interface.
public class InterfacesImpl
implements InterfaceA,
InterfaceB, InterfaceC {
@Override
public void doSomething() {
System.out.println("doSomething
implementation of concrete class");
}
public static void main(String[] args) {
InterfaceA
objA = new InterfacesImpl();
InterfaceB
objB = new InterfacesImpl();
InterfaceC
objC = new InterfacesImpl();
//all
the method calls below are going to same concrete implementation
objA.doSomething();
objB.doSomething();
objC.doSomething();
}
}
Did you noticed that every time I am overriding any
superclass method or implementing any interface method, I am using @Override
annotation, it’s one of the three built-in java annotations and we shouldalways use override annotation when overriding any
method.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.