Java: Override protected String

Java: Override protected String

Actually, others have answered your question. In case, you are really new to Java struggling to figure it out, the simplest answer to your question is just put your above mentioned statement in the constructor of the derived class:

  1. Solution one (actually bad solution):

    public class MySomething extends Something {
        public MySomething() {
            changeMe = that
        }
    }
    
  2. A better solution for your problem is to define a setter method in the class Something as follows (in case you have access to its source code):

    public void setChangeMe(String newValue) {
        changeMe = newValue;
    }
    

and you can change the value by calling

Something s = new Something();
s.setChangeMe(that);

the word override is a hint for the compiler, with that you let it know that youre writing code that at your own way implements the method of a parent class or the interface.

having said that overriding a variable/attribute/field is a wrong use of the terminology, and makes not much sense

to answer your question: you can access toso the changeMe object because it is not defined as private… so you can change the value directly..

Example:

public static void main(String args[])   {
    MySomething ms = new MySomething();
    System.out.println(ms.changeMe);
    ms.changeMe = that;
    System.out.println(ms.changeMe);
}

Java: Override protected String

Leave a Reply

Your email address will not be published. Required fields are marked *