In C++, you can extends many classes, so what's the advantages of this design in Java that a class can only extends one class ? Since interface is a pure kind of class(abstract class actually), why not limit the number of interfaces implementation just like class extension ?
In Java, multiple inheritances are not allowed due to ambiguity. Therefore, a class can extend only one class to avoid ambiguity.
Extending Multiple Interfaces A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not classes, however, and an interface can extend more than one parent interface. The extends keyword is used once, and the parent interfaces are declared in a comma-separated list.
An interface can extend other interfaces, just as a class subclass or extend another class. However, whereas a class can extend only one other class, an interface can extend any number of interfaces. The interface declaration includes a comma-separated list of all the interfaces that it extends.
The reason behind this is to prevent ambiguity. Consider a case where class B extends class A and Class C and both class A and C have the same method display(). Now java compiler cannot decide, which display method it should inherit. To prevent such situation, multiple inheritances is not allowed in java.
Being able to extend only one base class is one way of solving the diamond problem. This is a problem which occurs when a class extends two base classes which both implement the same method - how do you know which one to call?
A.java:
public class A {
public int getValue() { return 0; }
}
B.java:
public class B {
public int getValue() { return 1; }
}
C.java:
public class C extends A, B {
public int doStuff() {
return super.getValue(); // Which superclass method is called?
}
}
Since interfaces cannot have implementations, this same problem does not arise. If two interfaces contain methods that have identical signatures, then there is effectively only one method and there still is no conflict.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With