First of all, think about this scenario. If class A now inherits class B and class C, and the test() method exists in both class B and class C, then when the class A object calls the test() method, What about calling test() of class B? Or what about test() of class C? There is no answer, so multiple inheritance is not allowed in Java.
However, interfaces in Java can be multi-inherited, for example:
public interface A { void test(); } public interface B { void test(); } public interface C extends A, B{ }
Why can interfaces be inherited?
Because A, B, and C are all interfaces, even if the test method is defined in both interfaces A and B, because the interface only declares the method, it is not actually implemented. method, so it will not be a problem for the C interface. For the C interface, it just inherits the declaration of the same test() method. When using it, the implementation class of the C interface is required. Just implement this test() method.
public class C1 implements C{ public void test() { System.out.println("hello Hoeller"); } }So isn’t there a default method in the interface? Can't we also implement methods in interfaces? Let’s test it directly:
public interface A { default void test() { System.out.println("a"); } } public interface B { default void test() { System.out.println("b"); } } public interface C extends A, B{ }At this time, the C interface will compile and report an error. The error message is:
com.hoeller.C inherits unrelated defaults for test () from types com.hoeller.A and com.hoeller.BIt doesn’t matter whether it is translated or not. Anyway, an error is reported, indicating that the C interface cannot inherit the default method test() in both interfaces at the same time. .
The above is the detailed content of Why does Java not support multiple inheritance?. For more information, please follow other related articles on the PHP Chinese website!