看板 Translate-CS 關於我們 聯絡資訊
原文網址:http://www.javacodegeeks.com/2013/03/ introduction-to-default-methods-defender-methods-in-java-8.html 譯文網址:http://blog.dontcareabout.us/2013/03/java-8-default-method.html BBS 版以 markdown 撰寫 ______________________________________________________________________ 我們都知道 Java 裡頭的 interface 僅包含 method 的宣告、並沒有實作的部份, 任何 implement interface 但又不是 abstract class 的 class 必須提供這些 method 實作。 看看下面這個例子: public interface SimpleInterface { public void doSomeWork(); } class SimpleInterfaceImpl implements SimpleInterface{ @Override public void doSomeWork() { System.out.println("Do Some Work implementation in the class"); } public static void main(String[] args) { SimpleInterfaceImpl simpObj = new SimpleInterfaceImpl(); simpObj.doSomeWork(); } } 如果在 `SimpleInterface` 裡頭加一個新的 method 會怎樣? public interface SimpleInterface { public void doSomeWork(); public void doSomeOtherWork(); } 在嘗試 compile 的時候會得到這個結果: $javac .\SimpleInterface.java .\SimpleInterface.java:18: error: SimpleInterfaceImpl is not abstract and does not override abstract method doSomeOtherWork() in SimpleInterface class SimpleInterfaceImpl implements SimpleInterface{ ^ 1 error 這個限制導致要拓展、加強既有的 interface 跟 API 簡直難上加難。 在補強 Java 8 的 Collection API 以支援 lambda expression 時也遇到同樣困擾。 為了解決這個限制,Java 8 導入一個稱為 default method 的新觀念, 也有人稱之為 defender method 或 virtual extension method。 default method 會有預設的實作內容, 將有助於在不影響既有程式碼的前提下改善 interface。 看看這個例子就了解了: public interface SimpleInterface { public void doSomeWork(); //interface 中的 default method 要用「default」這個關鍵字 default public void doSomeOtherWork(){ System.out.println( "DoSomeOtherWork implementation in the interface" ); } } class SimpleInterfaceImpl implements SimpleInterface{ @Override public void doSomeWork() { System.out.println("Do Some Work implementation in the class"); } /* * 不需要提供 doSomeOtherWork 的實作了 */ public static void main(String[] args) { SimpleInterfaceImpl simpObj = new SimpleInterfaceImpl(); simpObj.doSomeWork(); simpObj.doSomeOtherWork(); } } 輸出結果會是: Do Some Work implementation in the class DoSomeOtherWork implementation in the interface 這裡很簡短地介紹了 default,想要更深入了解的可以參考[這份文件]。 [這份文件]: http://cr.openjdk.java.net/~briangoetz/ lambda/Defender%20Methods%20v4.pdf -- 錢鍾書: 說出來的話 http://www.psmonkey.org 比不上不說出來的話 Java 版 cookcomic 版 只影射著說不出來的話 and more...... -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.25.4.190