How to hide a static variable in Java

aro*_*aks 5 java inheritance binding

I have three classes with same methods and only constants are different. So what I wanted is to create one base class, which contains all the methods and to add three child classes which contain only constant variables. It looks like it is not possible to do so because of the dynamic binding. Please look at the example:

public class Parent {
    static String MY_CONSTANT = "bla bla";
    public void printSomething() {
        System.out.println(MY_CONSTANT);
    }
}

public class Child extends Parent {
    static String MY_CONSTANT = "hello world";
}

public class Greetings {
    public static void main(String[] args) {
        Child hey = new Child();
        hey.printSomething();
    }
}
Run Code Online (Sandbox Code Playgroud)

The output is "bla bla", but I want the output to be "hello world".

Is there some solution for this problem?

ern*_*t_k 1

Java中如何隐藏静态变量?

这就是您可以对变量执行的所有操作:隐藏它们。虽然变量可以继承,但不能覆盖。

由于实际值是特定于类的并且是静态的,因此在这种情况下重用方法的唯一方法是使其接受参数:

public class Parent {
    static String MY_CONSTANT = "bla bla";

    public void printSomething(String something) {
        System.out.println(something);
    }

    //Essentially, Parent.MY_CONSTANT becomes just the default
    public void printSomething() {
        System.out.println(MY_CONSTANT);
    }
}
Run Code Online (Sandbox Code Playgroud)

子进程可以选择发送的内容(覆盖基本上是为了重用 API):

public class Child extends Parent{
    static String MY_CONSTANT = "hello world";

    @Override
    public void printSomething() {
        //MY_CONSTANT is hidden and has "hello world"
        super.printSomething(MY_CONSTANT); 
    }
}
Run Code Online (Sandbox Code Playgroud)

上述设计允许来自测试类的调用以可预测的方式(或者更确切地说,直观地)运行:

Child hey = new Child();
//Behaves as Child.
hey.printSomething();
Run Code Online (Sandbox Code Playgroud)

编辑:由于 getter 是一个实例方法(可以理解,因为您依赖于实例类型来读取正确的值),因此您可以向子级公开该字段或 setter,并且所有类型的隐藏都将被完全抑制:

public class Parent {
    protected String myConstant = "bla bla";

    public void printSomething() {
        System.out.println(this.myConstant);
    }
}
Run Code Online (Sandbox Code Playgroud)

孩子们只需在初始化块中设置该值:

public class Child extends Parent{
    public Child() {
        myConstant = "hello world";
    }
}
Run Code Online (Sandbox Code Playgroud)