是否強制要求在 Java 中覆蓋介面的預設方法?
Java8 中引入了預設方法。這些方法不像其他抽象方法,它們具有一個預設實現。如果你在介面中擁有預設方法,則在實現此介面的類中不是強制覆蓋(提供主體)它。
簡而言之,你可以使用實現類的物件訪問介面的預設方法。
示例
interface MyInterface{ public static int num = 100; public default void display() { System.out.println("display method of MyInterface"); } } public class InterfaceExample implements MyInterface{ public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.display(); } }
輸出
display method of MyInterface
但是,當你的類實現兩個介面,並且它們都具有同名和原型的函式時,你必須覆蓋此方法,否則會生成一個編譯時錯誤。
示例
interface MyInterface1{ public static int num = 100; public default void display() { System.out.println("display method of MyInterface1"); } } interface MyInterface2{ public static int num = 1000; public default void display() { System.out.println("display method of MyInterface2"); } } public class InterfaceExample implements MyInterface1, MyInterface2{ public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); // obj.display(); } }
編譯時錯誤
InterfaceExample.java:14: error: class InterfaceExample inherits unrelated defaults for display() from types MyInterface1 and MyInterface2 public class InterfaceExample implements MyInterface1, MyInterface2{ ^ 1 error
要解決此問題,你需要覆蓋實現類中的 display() 方法(或兩個方法)−
示例
interface MyInterface1{ public static int num = 100; public default void display() { System.out.println("display method of MyInterface1"); } } interface MyInterface2{ public static int num = 1000; public default void display() { System.out.println("display method of MyInterface2"); } } public class InterfaceExample implements MyInterface1, MyInterface2{ public void display() { MyInterface1.super.display(); //or, MyInterface2.super.display(); } public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.display(); } }
輸出
display method of MyInterface1 display method of MyInterface2
廣告