我有三个具有相同方法的类,只有常量不同。所以我想要的是创建一个包含所有方法的基类,并添加三个只包含常量变量的子类。由于动态绑定(bind),看起来不可能这样做。请看例子:
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();
}
}
输出是“bla bla”,但我希望输出是“hello world”。
这个问题有什么解决办法吗?
最佳答案
您必须覆盖 printSomething()
方法:
public class Child extends Parent {
static String MY_CONSTANT = "hello world";
@Override
public void printSomething() {
System.out.println(MY_CONSTANT);
}
}
不过,拥有一个返回静态变量值的方法可能更简洁。然后您可以覆盖该方法,并从基类调用它:
public class Parent {
static String MY_CONSTANT = "bla bla";
public String getConstant() {
return Parent.MY_CONSTANT;
}
public void printSomething() {
System.out.println(getConstant());
}
}
public class Child extends Parent {
static String MY_CONSTANT = "hello world";
@Override
public String getConstant() {
return Child.MY_CONSTANT;
}
}
public class Greetings {
public static void main(String[] args) {
Child hey = new Child();
hey.printSomething();
}
}
关于java - 如何在 Java 中隐藏静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50248337/