假设我有以下情况:
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() { ... }
}
Java 接口不能扩展类,这是有道理的,因为类包含无法在接口中指定的实现细节。
处理这个问题的正确方法是将接口与实现完全分离,将Vehicle
也进入一个界面。这Car
ETC。可以延长Vehicle
接口强制程序员实现相应的方法。如果您想在所有人之间共享代码Vehicle
实例,那么您可以使用(可能是抽象的)类作为任何需要实现该接口的类的父类。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)