我有一类“Character”,Character 是非静态的。我希望我的播放器类扩展 Character 但也是静态的。
我基本上希望所有其他对象和类都能够访问播放器,而无需创建和传递播放器实例。
实现这一目标的最佳原因是什么?
最佳答案
我能想到的唯一好的方法实际上不是扩展而是包装器:
class Player {
private final static Charachter me = new Character();
public static doSomething(){ me.doSomething(); }
}
当然你也可以扩展和包装:
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(); }
}
或者,实际上,由于您的目标只是保证只有一个玩家对象,您可以忘记将方法设为静态,而是隐藏构造函数:
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(); }
}
这确保了获得 Player
的唯一方法是调用 Player.getPlayer()
,并且它始终为您提供相同的对象(您永远不会创建更多比一个)。
关于Java - 非静态类的扩展静态类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6320190/