[翻译] 简介 Java 8 的 default method

楼主: PsMonkey (痞子军团团长)   2013-03-27 18:06:51
原文网址: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

Links booklink

Contact Us: admin [ a t ] ucptt.com