Documentation

The Java™ Tutorials
Hide TOC
Using an Interface as a Type将接口用作类型
Trail: Learning the Java Language
Lesson: Interfaces and Inheritance
Section: Interfaces

Using an Interface as a Type将接口用作类型

When you define a new interface, you are defining a new reference data type. 定义新接口时,您正在定义新的引用数据类型。You can use interface names anywhere you can use any other data type name. 您可以在任何可以使用任何其他数据类型名称的地方使用接口名称。If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface.如果定义类型为接口的引用变量,则分配给它的任何对象都必须是实现该接口的类的实例。

As an example, here is a method for finding the largest object in a pair of objects, for any objects that are instantiated from a class that implements Relatable:例如,这里有一个方法,用于查找一对对象中最大的对象,对于从实现Relatable的类实例化的任何对象:

public Object findLargest(Object object1, Object object2) {
   Relatable obj1 = (Relatable)object1;
   Relatable obj2 = (Relatable)object2;
   if ((obj1).isLargerThan(obj2) > 0)
      return object1;
   else 
      return object2;
}

By casting object1 to a Relatable type, it can invoke the isLargerThan method.通过将object1强制转换为一个Relatable类型,它可以调用isLargerThan方法。

If you make a point of implementing Relatable in a wide variety of classes, the objects instantiated from any of those classes can be compared with the findLargest() method—provided that both objects are of the same class. 如果您注意在各种各样的类中实现Relatable,那么从这些类中实例化的对象可以与findLargest()方法—前提是两个对象属于同一类。Similarly, they can all be compared with the following methods:同样,它们都可以与以下方法进行比较:

public Object findSmallest(Object object1, Object object2) {
   Relatable obj1 = (Relatable)object1;
   Relatable obj2 = (Relatable)object2;
   if ((obj1).isLargerThan(obj2) < 0)
      return object1;
   else 
      return object2;
}

public boolean isEqual(Object object1, Object object2) {
   Relatable obj1 = (Relatable)object1;
   Relatable obj2 = (Relatable)object2;
   if ( (obj1).isLargerThan(obj2) == 0)
      return true;
   else 
      return false;
}

These methods work for any "relatable" objects, no matter what their class inheritance is. 这些方法适用于任何“相关”对象,无论它们的类继承是什么。When they implement Relatable, they can be of both their own class (or superclass) type and a Relatable type. 当它们实现Relatable时,它们可以是自己的类(或超类)类型,也可以是Relatable类型。This gives them some of the advantages of multiple inheritance, where they can have behavior from both a superclass and an interface.这给了他们多重继承的一些优势,在多重继承中,他们可以同时拥有超类和接口的行为。


Previous page: Implementing an Interface
Next page: Evolving Interfaces