Documentation

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

Interfaces接口

There are a number of situations in software engineering when it is important for disparate groups of programmers to agree to a "contract" that spells out how their software interacts.在软件工程中,有许多情况下,不同的程序员群体必须同意一份“合同”,该合同详细说明了他们的软件是如何交互的。Each group should be able to write their code without any knowledge of how the other group's code is written.每个小组都应该能够编写自己的代码,而不知道另一组的代码是如何编写的。Generally speaking, interfaces are such contracts.一般来说,接口就是这样的契约。

For example, imagine a futuristic society where computer-controlled robotic cars transport passengers through city streets without a human operator.例如,想象一个未来社会,计算机控制的机器人汽车在没有人工操作的情况下运送乘客穿过城市街道。Automobile manufacturers write software (Java, of course) that operates the automobile—stop, start, accelerate, turn left, and so forth.汽车制造商编写操作汽车的软件(当然是Java);停车、起步、加速、左转等等。Another industrial group, electronic guidance instrument manufacturers, make computer systems that receive GPS (Global Positioning System) position data and wireless transmission of traffic conditions and use that information to drive the car.另一个工业集团,电子导航仪器制造商,制造计算机系统,接收GPS(全球定位系统)位置数据和交通状况的无线传输,并使用这些信息驾驶汽车。

The auto manufacturers must publish an industry-standard interface that spells out in detail what methods can be invoked to make the car move (any car, from any manufacturer).汽车制造商必须发布一个行业标准界面,详细说明可以调用哪些方法使汽车移动(任何汽车,来自任何制造商)。The guidance manufacturers can then write software that invokes the methods described in the interface to command the car. Neither industrial group needs to know how the other group's software is implemented.然后,导航制造商可以编写软件,调用界面中描述的方法来指挥汽车。两个工业集团都不需要知道另一个集团的软件是如何实现的。In fact, each group considers its software highly proprietary and reserves the right to modify it at any time, as long as it continues to adhere to the published interface.事实上,每个集团都认为其软件具有高度的专有性,并保留随时对其进行修改的权利,只要它继续遵守已发布的界面。

Interfaces in JavaJava中的接口

In the Java programming language, an interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. 在Java编程语言中,接口是一种引用类型,类似于类,它只能包含常量、方法签名、默认方法、静态方法和嵌套类型。Method bodies exist only for default methods and static methods. 方法体仅存在于默认方法和静态方法中。Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces. 接口不能实例化—它们只能由类实现或由其他接口扩展Extension is discussed later in this lesson.本课程后面将讨论扩展。

Defining an interface is similar to creating a new class:定义接口类似于创建新类:

public interface OperateCar {

   // constant declarations, if any

   // method signatures
   
   // An enum with values RIGHT, LEFT
   int turn(Direction direction,
            double radius,
            double startSpeed,
            double endSpeed);
   int changeLanes(Direction direction,
                   double startSpeed,
                   double endSpeed);
   int signalTurn(Direction direction,
                  boolean signalOn);
   int getRadarFront(double distanceToCar,
                     double speedOfCar);
   int getRadarRear(double distanceToCar,
                    double speedOfCar);
         ......
   // more method signatures
}

Note that the method signatures have no braces and are terminated with a semicolon.请注意,方法签名没有大括号,并以分号结尾。

To use an interface, you write a class that implements the interface. 要使用接口,您需要编写一个实现该接口的类。When an instantiable class implements an interface, it provides a method body for each of the methods declared in the interface. 当一个可实例化类实现一个接口时,它为接口中声明的每个方法提供一个方法体。For example,例如

public class OperateBMW760i implements OperateCar {

    // the OperateCar method signatures, with implementation --
    // for example:
    public int signalTurn(Direction direction, boolean signalOn) {
       // code to turn BMW's LEFT turn indicator lights on
       // code to turn BMW's LEFT turn indicator lights off
       // code to turn BMW's RIGHT turn indicator lights on
       // code to turn BMW's RIGHT turn indicator lights off
    }

    // other members, as needed -- for example, helper classes not 
    // visible to clients of the interface
}

In the robotic car example above, it is the automobile manufacturers who will implement the interface. 在上面的机器人汽车示例中,是汽车制造商将实现该接口。Chevrolet's implementation will be substantially different from that of Toyota, of course, but both manufacturers will adhere to the same interface. 当然,雪佛兰的实施将与丰田有很大不同,但两家制造商将坚持相同的接口。The guidance manufacturers, who are the clients of the interface, will build systems that use GPS data on a car's location, digital street maps, and traffic data to drive the car. 导航制造商是该接口的客户,他们将构建使用汽车位置GPS数据、数字街道地图和交通数据驾驶汽车的系统。In so doing, the guidance systems will invoke the interface methods: turn, change lanes, brake, accelerate, and so forth.在这样做时,导航系统将调用接口方法:转弯、变道、制动、加速等。

Interfaces as APIs作为API的接口

The robotic car example shows an interface being used as an industry standard Application Programming Interface (API). 机器人汽车示例显示了一个用作行业标准应用程序编程接口(API)的接口。APIs are also common in commercial software products. API在商业软件产品中也很常见。Typically, a company sells a software package that contains complex methods that another company wants to use in its own software product. 通常,一家公司销售的软件包包含另一家公司希望在其软件产品中使用的复杂方法。An example would be a package of digital image processing methods that are sold to companies making end-user graphics programs. 一个例子是向制作最终用户图形程序的公司出售的一套数字图像处理方法。The image processing company writes its classes to implement an interface, which it makes public to its customers. 这家图像处理公司编写其类来实现一个接口,并向其客户公开该接口。The graphics company then invokes the image processing methods using the signatures and return types defined in the interface. 图形公司然后使用界面中定义的签名和返回类型调用图像处理方法。While the image processing company's API is made public (to its customers), its implementation of the API is kept as a closely guarded secret—in fact, it may revise the implementation at a later date as long as it continues to implement the original interface that its customers have relied on.虽然图像处理公司的API(向其客户)公开,但其API的实现却被视为一个严密保密的秘密;事实上,它可能会在以后修改实现,只要它继续实现其客户依赖的原始接口。


Previous page: Interfaces and Inheritance
Next page: Defining an Interface