我假设一个类具有多个继承层次结构,它可以分解为: 假设一架飞机有 4 种组合:
1. Subsonic & commercial
2. Subsonic & jet fighter
3. Supersonic & commercial
4. Supersonic & jet fighter
现在我的非面向对象类看起来像这样
Class Airplane {
Void SubsonicAndCommercial {
print
}
void subsonicAndJet {
}
void supersonicAndCommercial {
}
void supersonicAndJet {
}
}
现在我需要将飞机类分解为子类。最常见的方法是什么?
这将是一个 2 级层次结构吗?
IE
平面
Iface 亚音速,超音速延伸平面
4-Subclass Jet 延伸超音速,jet 延伸亚音速..等等
最佳答案
在 Java 中,类永远不能扩展多个类,因此这看起来像是接口(interface)的一项工作。您应该为亚音速、超音速、商业和战斗机制作界面。然后你可以像这样实现它们
public class SubCommercialPlane implements Subsonic, Commercial
public class SuperCommercialPlane implements Supersonic, Commercial
public class SubFighterPlane implements Subsonic, Fighter
public class SuperCommercialPlane implements Supersonic, Fighter
这可能是使用简单的 java 层次结构实现此目的的最佳方法。如果您想以更复杂的方式解决这个问题,请查看实体组件模型,这篇维基百科文章对此进行了很好的解释:
https://en.wikipedia.org/wiki/Entity%E2%80%93component%E2%80%93system
关于java - 如何构建两级继承层次结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44440430/