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.
Using a static method. Using private access modifier. Using default access modifier. Using the final keyword method.
Overriding is only applicable to methods but not to variables. In Java, if the child and parent class both have a variable with the same name, Child class's variable hides the parent class's variable, even if their types are different. This concept is known as Variable Hiding.
Explanation: To disallow a method from being overridden, specify final as a modifier at the start of its declaration. Methods declared as final cannot be overridden.
Because instance variables CANNOT be overridden in Java. In Java, only methods can be overridden.
declare your variable private, and use getter .
keep it private
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With