假设我有以下情况:有没有一种方法可以保证一个接口在Java中扩展一个类?
public abstract class Vehicle {
public void turnOn() { ... }
}
public interface Flier {
public void fly();
}
有没有办法,我可以保证,实现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() { ... }
}
接口扩展接口。 (摘要)类(部分)实现接口并扩展其他类。 – asgs
试试我的建议,你无法编译MySpecialMachine而不从车辆延伸! –