Home > Java > javaTutorial > Why does Java not support multiple inheritance?

Why does Java not support multiple inheritance?

王林
Release: 2023-05-13 10:04:14
forward
1027 people have browsed it

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{
}
Copy after login

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");
    }
}
Copy after login

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{
}
Copy after login
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.B

It 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!

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
Install JAVA
From 1970-01-01 08:00:00
0
0
0
Unable to install java
From 1970-01-01 08:00:00
0
0
0
Can java be used as the backend of the web?
From 1970-01-01 08:00:00
0
0
0
Is this in Java language?
From 1970-01-01 08:00:00
0
0
0
Help: JAVA encrypted data PHP decryption
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template