I'm writing a RTS Game in Java and have run into some problem with polymorphism. To describe my issue I'll list a few objects/classes in the game: (I will state what each of them should be able to do within brackets)
- Tank (Can move, can attack)
- Tower (Can attack)
- Factory (Can build tanks)
- Tree (Can be farmed)
- Tiger (Can move, can attack, can be farmed)
The ideal way to do it in my eyes would be a class for each unique ability i.e Movable, Attackable, Farmable, Constructible. This is different abilities that all of the listed objects have. And they are all a GameObject (highest class in hierarchy with common data for all objects).
Movable holds all code for moving an object (calculating speed, direction, new position and so on). Attackable holds code for following a target, firing, update fired shots etc. And same goes for the other ability classes.
So in my eyes this would be perfect:
public class Tank extends Movable, Attackable, GameObject {}
public class Tiger extends Movable, Attackable, Farmable, GameObject {}
Oviously Java doesn't allow for extending multiple classes. And I don't see how I could use interfaces to solve my polymorphism and class hierarchy issues.
Any ideas? The goal is of course not to repeat code that several objects in the game shares.