Java 8中的默认方法(Defender方法)简介
生活随笔
收集整理的這篇文章主要介紹了
Java 8中的默认方法(Defender方法)简介
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
我們都知道Java中的接口僅包含方法聲明,而沒有實現,并且任何實現該接口的非抽象類都必須提供實現。 讓我們看一個例子:
現在,如果我在SimpleInterface中添加新方法怎么辦?
public interface SimpleInterface {public void doSomeWork();public void doSomeOtherWork(); }如果我們嘗試編譯代碼,最終結果是:
$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這種限制使得幾乎不可能擴展/改進現有的接口和API。 在Java 8中增強Collections API以在API中支持lambda表達式時,面臨著同樣的挑戰。 為了克服此限制,Java 8中引入了一個稱為默認方法的新概念,該默認方法也稱為Defender方法或虛擬擴展方法。
默認方法是具有一些默認實現的那些方法,它們有助于在不破壞現有代碼的情況下擴展接口。 讓我們看一個例子:
public interface SimpleInterface {public void doSomeWork();//A default method in the interface created using 'default' keyworddefault public void doSomeOtherWork(){System.out.println('DoSomeOtherWork implementation in the interface');} }class SimpleInterfaceImpl implements SimpleInterface{@Overridepublic void doSomeWork() {System.out.println('Do Some Work implementation in the class');}/** Not required to override to provide an implementation * for 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 這是對默認方法的非常簡短的介紹。 在這里可以深入了解默認方法。
參考:來自JCG合作伙伴 Mohamed Sanaulla的Java 8中的默認方法(防御方法)簡介,網址為Experiences Unlimited 。
翻譯自: https://www.javacodegeeks.com/2013/03/introduction-to-default-methods-defender-methods-in-java-8.html
總結
以上是生活随笔為你收集整理的Java 8中的默认方法(Defender方法)简介的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ddos攻击手段教程(ddos攻击手法教
- 下一篇: 简易征收不用备案了吗(简易征收不备案可以