我们都知道Java中的接口仅包含方法声明,而没有实现,并且任何实现该接口的非抽象类都必须提供实现。 让我们看一个例子:
public interface SimpleInterface {public void doSomeWork();
}class SimpleInterfaceImpl implements SimpleInterface{@Overridepublic 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中添加新方法怎么办?
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