18.md 2.3 KB
Newer Older
W
init  
wizardforcel 已提交
1 2 3 4
# 什么是接口?

> 原文: [https://docs.oracle.com/javase/tutorial/java/concepts/interface.html](https://docs.oracle.com/javase/tutorial/java/concepts/interface.html)

W
wizardforcel 已提交
5
正如您已经了解的那样,对象通过它们公开的方法定义它们与外部世界的交互。方法与外界形成对象的*接口 _;例如,电视机正面的按钮是您与塑料外壳另一侧电线之间的接口。按“电源”按钮打开和关闭电视。
W
init  
wizardforcel 已提交
6 7 8

在最常见的形式中,接口是一组具有空体的相关方法。自行车的行为(如果指定为接口)可能如下所示:

W
wizardforcel 已提交
9
```java
W
init  
wizardforcel 已提交
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
interface Bicycle {

    //  wheel revolutions per minute
    void changeCadence(int newValue);

    void changeGear(int newValue);

    void speedUp(int increment);

    void applyBrakes(int decrement);
}

```

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

W
wizardforcel 已提交
26
```java
W
init  
wizardforcel 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
class ACMEBicycle implements Bicycle {

    int cadence = 0;
    int speed = 0;
    int gear = 1;

   // The compiler will now require that methods
   // changeCadence, changeGear, speedUp, and applyBrakes
   // all be implemented. Compilation will fail if those
   // methods are missing from this class.

    void changeCadence(int newValue) {
         cadence = newValue;
    }

    void changeGear(int newValue) {
         gear = newValue;
    }

    void speedUp(int increment) {
         speed = speed + increment;   
    }

    void applyBrakes(int decrement) {
         speed = speed - decrement;
    }

    void printStates() {
         System.out.println("cadence:" +
             cadence + " speed:" + 
             speed + " gear:" + gear);
    }
}

```

实现接口允许类对其承诺提供的行为变得更加正式。接口在类和外部世界之间形成契约,并且该合同在构建时由编译器强制执行。如果您的类声称实现了一个接口,那么该接口定义的所有方法必须出现在其源代码中才能成功编译该类。

* * *

**Note:** To actually compile the `ACMEBicycle` class, you'll need to add the `public` keyword to the beginning of the implemented interface methods. You'll learn the reasons for this later in the lessons on [Classes and Objects](../javaOO/index.html) and [Interfaces and Inheritance](../IandI/index.html).

* * *