如何继承静态字段并改变它的值? [英] How to inherit static field and change it's value?

查看:85
本文介绍了如何继承静态字段并改变它的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 的实例c $ c>变量,非静态方法可以通过常规覆盖执行所需的操作。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆