Java - Java接口

108 阅读2分钟

Java接口

想象一下在未来社会,由计算机控制的无人驾驶车辆在大街上驰骋,汽车制造商通过写代码来实现无人驾驶技术,(启动/停止/加速/转弯/向前等)。另一个工业集团,电子制导仪制造商,生产接收 GPS(全球定位系统)位置数据和无线传输交通状况的计算机系统,并使用这些信息来驾驶汽车。汽车制造商必须发布一个行业标准接口,详细说明可以调用哪些方法来使汽车移动(任何汽车,来自任何制造商)。然后,导航制造商可以编写软件,调用接口中描述的方法来指挥汽车。两个工业集团都不需要知道另一个集团的软件是如何实现的。 事实上,每个小组都认为其软件具有高度专有性,并保留随时修改它的权利,只要它继续遵守已发布的界面即可。

  1. Java语言的接口只能被类实现 implements
  2. Java语言的接口只能够被另一个接口继承 extend
  3. Java语言的接口不能被实例化

Java接口的代码示例

在Java中,接口像类一样是一个引用类型,可以包含:常量、方法声明、默认方法、静态方法、嵌套方法。方法体只存在默认方法和静态方法中。

public interface OperateCar {

   // constant declarations, if any

   // method signatures
   
   // An enum with values RIGHT, LEFT
   int turn(Direction direction,
            double radius,
            double startSpeed,
            double endSpeed);
   int changeLanes(Direction direction,
                   double startSpeed,
                   double endSpeed);
   int signalTurn(Direction direction,
                  boolean signalOn);
   int getRadarFront(double distanceToCar,
                     double speedOfCar);
   int getRadarRear(double distanceToCar,
                    double speedOfCar);
         ......
   // more method signatures
}

接口实现(普通的类需要实现接口中的所有方法):

public class OperateBMW760i implements OperateCar {

    // the OperateCar method signatures, with implementation --
    // for example:
    public int signalTurn(Direction direction, boolean signalOn) {
       // code to turn BMW's LEFT turn indicator lights on
       // code to turn BMW's LEFT turn indicator lights off
       // code to turn BMW's RIGHT turn indicator lights on
       // code to turn BMW's RIGHT turn indicator lights off
    }

    // other members, as needed -- for example, helper classes not 
    // visible to clients of the interface
}