Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Prevent override of a member variable

Tags:

java

oop

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.

like image 923
Erel Segal-Halevi Avatar asked Nov 15 '11 13:11

Erel Segal-Halevi


People also ask

How will you prevent the override method in Java?

Using a static method. Using private access modifier. Using default access modifier. Using the final keyword method.

Can you override member variables in Java?

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.

How do you prevent a method from overriding?

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.

Which member variable Cannot be override in Java?

Because instance variables CANNOT be overridden in Java. In Java, only methods can be overridden.


2 Answers

declare your variable private, and use getter .

like image 88
Molochdaa Avatar answered Sep 22 '22 02:09

Molochdaa


keep it private

like image 26
jmj Avatar answered Sep 18 '22 02:09

jmj