# 什么是接口？

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

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

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

```
interface Bicycle {

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

    void changeGear(int newValue);

    void speedUp(int increment);

    void applyBrakes(int decrement);
}

```

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

```
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).

* * *