Java: preventing member variable overrides

A useful feature of Java is the ability 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 have to tell you more about the scenario: I have a variable in the parent class that must be updated by child classes (so it should not be private). However, if the child class creates a variable with the same name, it THINKS that it updated the parent variable, even if 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.

+5
source share
2 answers

declare a private variable and use getter.

+9

private

+4

All Articles