Possible Duplicate:
extending from two classes
I’m currently trying to make a simple Mod for Minecraft and I basically need this code:
(I don’t want to edit many classes because I want my mod to be compatible with many other mods.)
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 */));
}
But you can’t extend more than one class…
The new EntityFishHook* wants a EntityPlayer and not a EntityModPlayer as param but the new EntityAISwimming method wants me to use an instance of EntityCreature as param. So I need to “extend” EntityPlayer AND EntityCreature and can’t just copy EntityPlayer and paste it as EntityModPlayer.
I already played around with Interfaces but I think this is something different so I can’t use this like “extends”.
Sorry @ everybody who doesn’t know Minecraft or can’t understand my english… (I’m german.)
Any ideas where I don’t have to change many / important classes like EntityTasks (because this would make my mod incompatible with other mods if they are editing the same class)?
*The method new EntityFishHook (EntityPlayer) does not really exist in Minecraft. I just used this as an example to explain it better. I hope you understood what I tried to explain, I’m sure it’s not easy :/
The correct idiom for Java ( and other single inheritance languages ) is to have two interfaces.
EntityPlayerandEntityCreaturethen you combine them into a single class thatImplementseach of the interfaces.Another approach is to use the
Composite Patternto create a single class that has all the methods from eachClassand have that class delegate each of the methods to instances of each of the internal classes owned by the single class that combines the interfaces. This works if the client code doesn’t expect either of the interfaces at a language level or with a duck typing language like Python.You can combine both approaches two interfaces with the
Composite Patternand have theCompositeobject delegate to individual implementations of eachInterface, this would enable easy dependency injection; making your code more flexible using something like Google Guice.