Documentation

The Java™ Tutorials
Hide TOC
Evolving Interfaces演化接口
Trail: Learning the Java Language
Lesson: Interfaces and Inheritance
Section: Interfaces

Evolving Interfaces演化接口

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 interface will break because they no longer implement the old interface. 如果进行此更改,那么所有实现旧DoIt接口的类都将中断,因为它们不再实现旧接口。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:您可以创建扩展DoItDoItPlus接口:

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.拥有实现了用新的默认或静态方法增强的接口的类的用户不必修改或重新编译它们以适应其他方法。


Previous page: Using an Interface as a Type
Next page: Default Methods