Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why Java class can extends only one class but implements many interfaces? [duplicate]

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 ?

like image 827
Bin Avatar asked Sep 18 '13 03:09

Bin


People also ask

Why we can implement multiple interfaces but only extend one class in Java?

In Java, multiple inheritances are not allowed due to ambiguity. Therefore, a class can extend only one class to avoid ambiguity.

Why an interface can extend more than one interface but a class can't extend more than one class?

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.

Why we can extend multiple interfaces in Java?

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.

Why a class Cannot extend more than one class in Java?

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.


1 Answers

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.

like image 165
Chris Hayes Avatar answered Sep 30 '22 17:09

Chris Hayes