假设我有一个抽象类Game
:
public abstract class Game
{
public static final int FRAME_LENGTH = 40;
public static int getFrameLength() {
return Game.FRAME_LENGTH; //What do I have to replace Game with?
}
}
还有App
扩展的类Game
:
public class App extends Game
{
private static final int FRAME_LENGTH = 50;
}
现在,App.main()
执行该方法后,它会打印出来,正如40
我所期望的那样50
,因为App
它覆盖了的值FRAME_LENGTH
。我猜我将不得不self
在Game
类中使用类似的东西,除了java没有self
。
我应该如何在App.FRAME_LENGTH
不事先知道子类将被调用的情况下访问静态属性App
?
好吧,基于第一个答案,我认为我必须稍微说明一下我的问题。
首先,我将的范围更改FRAME_LENGTH
为public
。为了这个问题,这使事情变得更容易。其次,我更改了getFrameLength
以前称为的方法main
。
我面临的问题:现在,我不知道哪些类将扩展Game
,Game
也不应该知道。
如果您查看代码,将可以看到Game.FRAME_LENGTH
is40
和App.FRAME_LENGTH
is 50
。Game.getFrameLength()
返回40
预期的结果,但是App.getFrameLength()
返回50
,我希望(或者更希望它)返回50
。
我的问题现在非常简单:在上面的代码中,我必须更改为什么return Game.FRAME_LENGTH;
,因此它返回正确的值(意味着FRAME_LENGTH
调用该方法的类的值),类似于self::$frameLength
PHP。
你不能访问App.FRAME_LENGTH
从主要方法varible,因为它被定义为private
给App
类。
另外,您不会覆盖变量值(通过扩展类)。类继承与static
成员无关
更新:
似乎您根本不需要static
修饰符。您需要执行以下操作:
public abstract class Game {
private final int FRAME_LENGTH = 40;
public int getFrameLength() {
return this.getValue(); //<-- Note the usage of the "this" keyword.
}
// Every subclass of Game must implement this method
// and return their specific FRAME_LENGTH value
public abstract int getValue();
}
通过使用this
关键字,我们实际上是在调用该类的当前实例(可以是子类)Game
。
现在,的示例子类Game
可以提供的其他值FRAME_LENGTH
。
public class App extends Game {
private final int FRAME_LENGTH = 50;
@Override
public int getValue() {
return FRAME_LENGTH;
}
}
现在,在调用时,new App().getFrameLength()
您实际上将返回App#getValue()
实现的结果,因此将收到50
。例如:
public static void main(String[] agrs) {
System.out.println(new App().getFrameLength());
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句