Java 教程是为 JDK 8 编写的。本页中描述的示例和实践未利用在后续版本中引入的改进。
正如你已经知道的那样,对象通过它们公开的方法来定义它们与外界的交互。方法与外界形成对象的 interface (接口);例如,电视机前面的按钮就是你和塑料外壳另一侧电视之间的接口。你按下 "电源" 按钮打开和关闭电视机。
在其最常见的形式中,接口是一组具有空体的相关方法。如果指定为接口,自行车的行为可能如下所示:
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);
}
}
实现一个接口允许一个类对它承诺提供的行为变得更加正式。接口形成了类和外部世界之间的契约,并且这个契约在编译器的编译时执行。如果你的类声明实现了一个接口,那么在该类成功编译之前,该接口定义的所有方法都必须出现在其源代码中。
ACMEBicycle 类,你需要将 public 关键字添加到实现的接口方法的开头。稍后你将在 Classes and Objects 和 Interfaces and Inheritance 的课程中了解原因。