如何在Java中使用静态扩展变量?

时间:2018-07-17 07:38:06

标签: java static-methods static-variables

我们有base类,如下所示:

public class Base {
    protected static string rule = "test_1";

    public static getRule(){
    /* get rule value from origin class*/
    }
}

我们有一些从base类扩展的类。例如:

public class Derived extends Base {
     static {
          rule = "test_2";
     }
}

现在,我们希望获取规则变量,但在某些情况下:

  • 如果用户调用Derived.getRule(),它将返回test_2
  • 如果derivedrule中的变量未初始化,则返回test_1
  • 我不想覆盖所有子类中的getRule来回答问题。

我该怎么办?

1 个答案:

答案 0 :(得分:1)

问题在于,一旦Derived类被使用(初始化),Base.rule就被更改,并且现在test_2随处可见,而与实际类无关。

因此该技术必须在没有静态的情况下(以这种形式)完成。有一个分类的类级别值。

public class Base {
    private static final String BASE_RULE = "test_1";

    public String getRule() {
        return BASE_RULE;
    }
}

public class Derived extends Base {
    private static final String DERIVED_RULE = "test_2";

    @Override
    public String getRule() {
        return DERIVED_RULE;
    }
}

或者,您可以使用标记器接口-但是它们不是互斥的,因此不适用于某些getCategory()。

public class Base implements Test1Category {
}

public class Derived extends Base implements Test2Category { ... }

if (base instanceof Test2Category) { ... }
相关问题