如何inheritance静态字段并改变它的值?

我正在开发程序/游戏,我有静态实用程序类和params。

class ParamsGeneral { public static final int H_FACTOR = 100; public static int MAX_SCORE = 1000; ... } 

然后我需要在某些特定情况下覆盖这些值,例如在分数有限的地图上播放。 所以我做了以下事情:

 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类?

PS:我知道我应该使默认类抽象并使用getter,我只是好奇是否有办法使值静态可访问。

您不能覆盖静态成员 – 在Java中,方法和字段都不能被覆盖。 但是,在这种情况下,您看起来不需要执行任何操作:因为在par变量中有一个ParamsGeneral实例,非静态方法可以使用常规覆盖执行您需要的操作。

 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(); } 

我不会将子类用于一般游戏与有限游戏。 我会使用枚举,如:

 public enum Scores { GENERAL (1000), LIMITED (500), UNLIMITED (Integer.MAX_INT); private int score; private Scores(int score) { this.score = score; } public int getScore() { return score; } } 

然后,在构建游戏时,您可以:

 Params generalParams = new Params(Scores.GENERAL); Params limitedParams = new Params(Scores.LIMITED); 

等等。

这样做可以让您在保持价值集中的同时改变游戏的本质。 想象一下,如果您想到的每种类型的参数都必须创建一个新类。 它可能变得非常复杂,你可能有数百个课程!

最简单的解决方案是:

 class ParamsGeneral { public static final int H_FACTOR = 100; public static final int MAX_SCORE = 1000; public static final int MAX_SCORE_LIMITED = 500; ... } class Player { int maxScore; public Player() { if(onLimitedMap()){ maxScore = ParamsGeneral.MAX_SCORE_LIMITED; } else { maxScore = ParamsGeneral.MAX_SCORE; } } public boolean isWinner() { if(this.score == this.maxScore) { return true; } return false; } } 

无需拥有ParamsGeneral的实例,它只是游戏静态定义的集合。

MAX_SCORE是公共静态getter的私有静态; 然后你可以调用ParamsGeneral.getMaxScoreParamsLimited.getMaxScore ,你将分别获得1000和500