The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
Consider an interface that you have developed called 考虑一个你称之为DoIt
:DoIt
的接口:
public interface DoIt { void doSomething(int i, double x); int doSomethingElse(String s); }
Suppose that, at a later time, you want to add a third method to 假设稍后您想向DoIt
, so that the interface now becomes:DoIt
添加第三个方法,这样接口现在就变成:
public interface DoIt { void doSomething(int i, double x); int doSomethingElse(String s); boolean didItWork(int i, double x, String s); }
If you make this change, then all classes that implement the old 如果进行此更改,那么所有实现旧DoIt接口的类都将中断,因为它们不再实现旧接口。DoIt
interface will break because they no longer implement the old interface. Programmers relying on this interface will protest loudly.依赖此接口的程序员将大声抗议。
Try to anticipate all uses for your interface and specify it completely from the beginning. 尝试预测接口的所有用途,并从一开始就完全指定它。If you want to add additional methods to an interface, you have several options. 如果要向接口添加其他方法,有几个选项。You could create a 您可以创建扩展DoItPlus
interface that extends DoIt
:DoIt
的DoItPlus
接口:
public interface DoItPlus extends DoIt { boolean didItWork(int i, double x, String s); }
Now users of your code can choose to continue to use the old interface or to upgrade to the new interface.现在,代码的用户可以选择继续使用旧接口或升级到新接口。
Alternatively, you can define your new methods as default methods. 或者,您可以将新方法定义为默认方法。The following example defines a default method named 以下示例定义了名为didItWork
:didItWork
的默认方法:
public interface DoIt { void doSomething(int i, double x); int doSomethingElse(String s); default boolean didItWork(int i, double x, String s) { // Method body } }
Note that you must provide an implementation for default methods. 请注意,必须为默认方法提供实现。You could also define new static methods to existing interfaces. 您还可以为现有接口定义新的静态方法。Users who have classes that implement interfaces enhanced with new default or static methods do not have to modify or recompile them to accommodate the additional methods.拥有实现了用新的默认或静态方法增强的接口的类的用户不必修改或重新编译它们以适应其他方法。