I have an abstract class Moveable with the method abstract void move() which is extended by the class Bullet and the abstract class Character, and Character is extended by the class Survivor and the class Zombie. In Survivor and Bullet the move() method doesnt require any parameters while in the class Zombie the move() method depends on the actual position of the survivor. The survivor and multiple zombies are created in the class Gui.
I wanted to access the survivor in Zombie – what’s the best way of doing this? In Gui i wrote a method getSurvivor() but i don’t see how to access this method in Zombie?
I am aware that as a workaround i could just pass a [Survivor survivor] as parameter in move() and ignore it in Bullet and Survivor, but that feels so … bad practice.
It depends where your Survivor is being held. Your Zombie will need a reference to a Survivor from somewhere – what does it need it for? Who should be responsible for providing this?
It sounds like your
Guiis doing too much actually, I’d prefer to have a class called something likeGameStatethat manages the positions and then just have the Gui handle the output. In any case, if there’s a single survivor you can simply have agetSurvivor()method on your Gui/Gamestate – and the Zombie should probably have a reference to the current game state that it’s part of. Alternatively you could make the GameState a singleton, and the Zombies could access it that way.Edit: In response to your comment, perhaps something like this:
In any case, the Zombie will have to obtain a reference to something that knows how to get the survivor. An alternative option would be to have the Survivor passed directly into the Zombie, but that doesn’t feel quite as clean somehow. It might be a viable option if Zombies must always have one and exactly one Survivor, but that feels like an artificial limitation.