A useful feature in Java is the option to declare a member method as final, so that it cannot be overridden in descendant classes. Is there something similar for member variables?
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!
}
EDIT: sorry, I should elaborate more on the scenario: I have a variable in the parent class, that should be updated by child classes (therefore it must not be private). However, if a child class creates a variable with the same name, it will THINK that it has updated the parent variable, even though it updated its own copy:
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
}
}
This is what I want to prevent.
declare your variable private, and use getter .