Java 中的防禦方法或虛擬方法是什麼?
Java 中的介面中的預設方法也稱為防禦方法或虛擬方法。
防禦方法/虛擬方法是那些在介面中具有預設實現的方法。你可以使用 default 關鍵字定義防禦方法/虛擬方法,如下所示 -
default void display() { System.out.println("This is a default method"); }
無需在實現的類中實現這些防禦方法/虛擬方法,你可以直接呼叫它們。
如果你有一個由某些類實現的介面,並且你希望在其中新增一個新方法。
然後,你需要在實現該介面的所有 exiString 類中實現這個新新增的方法。這是需要很多工作的。
為解決這個問題,你可以為所有新實現的方法編寫一個預設/防禦/虛擬方法。
示例
以下 Java 示例演示了在 Java 中使用預設方法。
interface sampleInterface{ public void demo(); default void display() { System.out.println("This is a default method"); } } public class DefaultMethodExample implements sampleInterface{ public void demo() { System.out.println("This is the implementation of the demo method"); } public static void main(String args[]) { DefaultMethodExample obj = new DefaultMethodExample(); obj.demo(); obj.display(); } }
輸出
This is the implementation of the demo method This is a default method
廣告