如何继承静态字段并更改其值? [英] How to inherit static field and change it's value?
问题描述
我正在开发带有参数的静态实用程序类的程序/游戏.
I'm working on program/game where I have static utility class with params.
class ParamsGeneral {
public static final int H_FACTOR = 100;
public static int MAX_SCORE = 1000;
...
}
然后我需要在某些特定情况下覆盖此值,例如在分数有限的地图上玩.所以我做了以下:
then I need to override this values in some specific cases, for example playing on map with limited score. So I did following:
class ParamsLimited extends ParamsGeneral {
public static int MAX_SCORE = 500;
// other params stay same
}
预期用途如下:
class Player {
ParamsGeneral par;
public Player() {
if(onLimitedMap()){
par = new ParamLimited();
}
}
public boolean isWinner() {
if(this.score == par.MAX_SCORE) {
return true;
}
return false;
}
}
我还没有真正测试过这段代码,因为 IDE 抱怨通过实例调用静态字段以及字段隐藏.我清楚地看到这段代码很臭,那么有没有办法实现这一点,或者我必须单独编写每个param类?
I haven't actually tested this code, because IDE is complaining about calling static field through instance and also about field hiding. I clearly see that this code is stinks, so is there a way to achieve this or do I have to write each param class separately?
PS:我知道我应该使默认类抽象并使用 getter,我只是想知道是否有办法使这些值静态访问.
PS: I know I shoud make the default class abstract and use getters, I'm just curious if there is a way to make the values accesible statically.
推荐答案
您不能覆盖静态成员 - 在 Java 中,方法和字段都不能被覆盖.但是,在这种情况下,您似乎不需要执行任何操作:由于您在 par
变量中有一个 ParamsGeneral
实例,因此非静态方法将使用常规覆盖执行您需要的操作.
You cannot override static members - in Java, neither methods nor fields could be overriden. However, in this case it does not look like you need to do any of that: since you have an instance of ParamsGeneral
in the par
variable, a non-static method would do what you need with the regular override.
class ParamsGeneral {
public int getMaxScore() {
return 1000;
}
}
class ParamsLimited extends ParamsGeneral {
@Override public int getMaxScore() {
return 500;
}
}
...
public boolean isWinner() {
// You do not need an "if" statement, because
// the == operator already gives you a boolean:
return this.score == par.getMaxScore();
}
这篇关于如何继承静态字段并更改其值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!