mat*_*ots 25 java inheritance interface
假设我有以下情况:
public abstract class Vehicle {
public void turnOn() { ... }
}
public interface Flier {
public void fly();
}
Run Code Online (Sandbox Code Playgroud)
有没有办法可以保证任何实现的类都Flier必须扩展Vehicle?我不想创建Flier一个抽象类,因为我希望能够以类似的方式混合其他一些接口.
例如:
// I also want to guarantee any class that implements Car must also implement Vehicle
public interface Car {
public void honk();
}
// I want the compiler to either give me an error saying
// MySpecialMachine must extend Vehicle, or implicitly make
// it a subclass of Vehicle. Either way, I want it to be
// impossible to implement Car or Flier without also being
// a subclass of Vehicle.
public class MySpecialMachine implements Car, Flier {
public void honk() { ... }
public void fly() { ... }
}
Run Code Online (Sandbox Code Playgroud)
thk*_*ala 29
Java接口不能扩展类,这是有道理的,因为类包含无法在接口中指定的实现细节.
处理此问题的正确方法是通过转换Vehicle为接口来完全将接口与实现分开.所述Car等可以扩展Vehicle接口以迫使程序员执行相应的方法.如果要在所有Vehicle实例之间共享代码,则可以使用(可能是抽象的)类作为需要实现该接口的任何类的父类.
您可以重新排列类和接口,如下所示:
public interface IVehicle {
public void turnOn();
}
public abstract class Vehicle implements IVehicle {
public void turnOn() { ... }
}
public interface Flier extends IVehicle {
public void fly();
}
Run Code Online (Sandbox Code Playgroud)
这样,所有实现Flier都保证实现车辆的协议,即IVehicle.