如您所知,对象通过其公开的方法定义了它们与外界的交互。方法形成对象与外界的接口(__interface ;例如,电视机正面的按钮,是您与塑料外壳另一侧的电线之间的接口。您按下“电源”按钮可以打开和关闭电视。
    在最常见的形式中,接口是一组具有空主体的相关方法。如果将自行车的行为指定为接口,则可能如下所示:

    1. interface Bicycle {
    2. // wheel revolutions per minute
    3. void changeCadence(int newValue);
    4. void changeGear(int newValue);
    5. void speedUp(int increment);
    6. void applyBrakes(int decrement);
    7. }

    要实现此接口,您的类名将更改(以特定品牌的自行车为例,例如ACMEBicycle),并且您可以在类声明中使用implements(实现)关键字:

    1. class ACMEBicycle implements Bicycle {
    2. int cadence = 0;
    3. int speed = 0;
    4. int gear = 1;
    5. // The compiler will now require that methods
    6. // changeCadence, changeGear, speedUp, and applyBrakes
    7. // all be implemented. Compilation will fail if those
    8. // methods are missing from this class.
    9. void changeCadence(int newValue) {
    10. cadence = newValue;
    11. }
    12. void changeGear(int newValue) {
    13. gear = newValue;
    14. }
    15. void speedUp(int increment) {
    16. speed = speed + increment;
    17. }
    18. void applyBrakes(int decrement) {
    19. speed = speed - decrement;
    20. }
    21. void printStates() {
    22. System.out.println("cadence:" +
    23. cadence + " speed:" +
    24. speed + " gear:" + gear);
    25. }
    26. }

    实现接口,可以使类对其承诺提供的行为变得更加正式。接口在类和外部世界之间形成契约,并且该契约在编译时由编译器强制执行。如果您的类声称要实现一个接口,则在成功编译该类之前,该接口定义的所有方法都必须出现在其源代码中。


    注意: 实际上,要编译ACMEBicycle类,您需要将public关键字添加到已实现的接口方法的开头。稍后将在“ 类和对象接口和继承 ”课程中,了解造成这种情况的原因 。