多繼承會產生鑽石問題(菱形繼承)
- 類 B 和類 C 繼承自類 A,且都重寫了類 A 中的同一個方法
- 類 D 同時繼承了類 B 和類 C
- 對於類 B、C 重寫的類 A 中的方法,類 D 會繼承哪一個?這里就會產生歧義
- 考慮到這種二義性問題,Java 不支持多重繼承
Java 支持類實現多接口
- 接口中的方法是抽象的,一個類實現可以多個接口
- 假設這些接口中存在相同方法(方法名與參數相同),在實現接口時,這個方法需要實現類來實現,並不會出現二義性的問題
從 JDK1.8 開始,接口中允許有靜態方法和方法默認實現。當檢測到實現類中實現的多個接口中有相同的默認已實現的方法,編譯報錯
PS:在JDK 1.5 上實踐,接口可以多繼承接口
package constxiong.interview; /** * 測試繼承多接口,實現相同方法 * 從 JDK1.8 開始,接口中允許有靜態方法和方法默認實現 * 當檢測到實現類中實現的多個接口中有相同的默認已實現的方法,編譯報錯 * @author ConstXiong * @date 2019-11-21 10:58:33 */ public class TestImplementsMulitInterface implements InterfaceA, InterfaceB { public void hello() { System.out.println("hello"); } } interface InterfaceA { void hello(); static void sayHello() { System.out.println("InterfaceA static: say hello"); } default void sayBye() { System.out.println("InterfaceA default: say bye"); } } interface InterfaceB { void hello(); static void sayHello() { System.out.println("InterfaceB static: say hello"); } // default void sayBye() { // System.out.println("InterfaceB default: say bye"); // } }
- Java 自學經歷
- Java 面試題 H5
- Java 面試題小程序

