什么是接口?

原文: https://docs.oracle.com/javase/tutorial/java/concepts/interface.html

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

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

  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. }

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


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 and Interfaces and Inheritance.