Possible Duplicate:
extending from two classes
我目前正在尝试为 Minecraft 制作一个简单的 Mod,我基本上需要以下代码:
(我不想编辑很多类,因为我希望我的 mod 与许多其他 mod 兼容。)
public class EntityModPlayer extends EntityPlayer, EntityCreature
{
super(par1World);
fishHook = new EntityFishHook(this /* has to be EntityPlayer */);
tasks.addTask(0, new EntityAISwimming(this /* has to be EntityCreature */));
}
但是你不能扩展多个类......
新 EntityFishHook* 需要 EntityPlayer 而不是 EntityModPlayer 作为参数,但新 EntityAISwimming 方法希望我使用 EntityCreature 实例作为参数。因此,我需要“扩展”EntityPlayer 和 EntityCreature,而不能只复制 EntityPlayer 并将其粘贴为 EntityModPlayer。
我已经尝试过接口(interface),但我认为这是不同的,所以我不能像“扩展”一样使用它。
抱歉@所有不了解 Minecraft 或听不懂我的英语的人...(我是德国人。)
有什么想法可以让我不必更改许多/重要类,例如EntityTasks(因为如果其他mod正在编辑同一类,这将使我的mod与其他mod不兼容)?
*new EntityFishHook (EntityPlayer) 方法在 Minecraft 中并不存在。我只是用这个作为例子来更好地解释它。我希望你明白我试图解释的内容,我确信这并不容易:/
最佳答案
Java(和其他单继承语言)的正确习惯用法是拥有两个接口(interface)。 EntityPlayer
和 EntityCreature
然后将它们组合成一个实现
每个接口(interface)的类。
另一种方法是使用Composite Pattern
创建一个类,该类包含每个Class
中的所有方法,并让该类将每个方法委托(delegate)给组合接口(interface)的单个类所拥有的每个内部类。如果客户端代码不需要语言级别的接口(interface)或使用鸭子类型语言(如 Python),则此方法有效。
您可以将这两种方法与Composite Pattern
结合起来,并将Composite
对象委托(delegate)给每个Interface
的单独实现,这将启用简单的依赖注入(inject);使用 Google Guice 等工具使您的代码更加灵活。
关于java - 扩展多个类的替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10609589/