Java 中一个有用的特性是可以选择将成员方法声明为 final,这样它就不能在后代类中被覆盖。成员变量有类似的东西吗?
class Parent {
public final void thisMethodMustRemainAsItIs() { /* ... */ }
public String thisVariableMustNotBeHidden;
}
class Child extends Parent {
public final void thisMethodMustRemainAsItIs() { /* ... */ } // Causes an error
public String thisVariableMustNotBeHidden; // Causes no error!
}
编辑:抱歉,我应该详细说明这个场景:我在父类中有一个变量,应该由子类更新(因此它不能是私有(private)的)。但是,如果子类创建了一个同名变量,它会认为它已经更新了父变量,即使它更新了自己的副本:
class Parent {
protected String myDatabase = null; // Should be updated by children
public void doSomethingWithMyDatabase() { /* ... */ }
}
class GoodChild extends Parent {
public GoodChild() {
myDatabase = "123";
doSomethingWithMyDatabase();
}
}
class BadChild extends Parent {
protected String myDatabase = null; // Hides the parent variable!
public BadChild() {
myDatabase = "123"; // Updates the child and not the parent!
doSomethingWithMyDatabase(); // NullPointerException
}
}
这就是我要防止的。
最佳答案
将您的变量声明为私有(private),并使用 getter 。
关于Java:防止覆盖成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8137055/