I have a class of 'Character', Character is non-static. I want my player class to extend Character but to also be static.
I basically want all other objects and classes to be able to access player without having to create and pass a player instance.
What's the best why to achieve this?
The only nice way I can think of is actually not an extension but a wrapper:
class Player { private final static Charachter me = new Character(); public static doSomething(){ me.doSomething(); } }
Of course you can also extend AND wrap:
class Player extends Character { private final static Player me = new Player(); // if you don't want anyone creating player objects // make the constructor private: private Player(){ super(); } public void doSomething(){ // stuff } public static void staticDoSomething(){ me.doSomething(); } }
Or, actually, since your goal is just to guarantee that there is a single player object, you can forget about making the methods static, but hide the constructor(s):
class Player extends Character { private static Player thePlayer = null; public static Player getPlayer(){ if( thePlayer == null ){ // Create the player thePlayer = new Player(); } // There is a valid player object, so return it. return thePlayer; } // hide the constructor(s) by making them private: private Player(){ super(); } }
That ensures that the only way to get a Player
is to call Player.getPlayer()
, and that it always gives you the same object (you never create more than one).
Really it seems like you just want a global variable. This is often accomplished through the Singleton pattern:
public class Player extends Character { private static final Player humanPlayer = new Player(); private Player() { } public static Player getHuman() { return humanPlayer; } //... } //... Player.getHuman().move(2);
There should be very little need for those methods in Player to be static. You're sacrificing good design for a tiny bit of convenience (that will probably bite you later anyway).
Personally I favour dependency injection over global state about 95% of the time. When a method needs to have access to the player, pass it in. That will let you test your code much more easily and will make your code more conducive to change.