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发行说明。
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()
methodprovided 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.这给了他们多重继承的一些优势,在多重继承中,他们可以同时拥有超类和接口的行为。