Is this proper way of extending classes in java?
所以我正在用LWJGL 2制作游戏,我的项目有4个类(Entity,AliveEntity,Player,Tree)。我希望我的实体(例如树木,蕨类植物,某些物品)扩展Entity类,而玩家又要扩展Entity和AliveEntity,这样玩家就可以拥有马力,速度,装备等了。所以现在看起来像这样:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | public class Entity{ public Entity(){ } public void methodForEveryEntity(){ } } public class AliveEntity extends Entity{ public AliveEntity(){ super(); } public void methodForOnlyLivingEntities(){ } } public class Player extends AliveEntity{ public Player(){ super(); } //it can use methods from AliveEntity and Entity classes } public class Tree extends Entity{ public Tree(){ super(); } //only methods from Entity class } |
我的方法正确吗?如果否,那么您能告诉我这样做的最佳方法是什么?我考虑过接口,但我不怎么喜欢它们...
据我所知,扩展时似乎是正确的。每当需要时,我都喜欢以层次结构的方式来考虑它。延伸会跟随它吗? Tree和AliveEntity都是Entity的一部分,Player是AliveEntity的一部分,尽管不是Tree的一部分,因此它仅扩展到AliveEntity。希望这会有所帮助。