Changing the value of superclass instance variables from a subclass

44,217

You have a lot of options.

  1. super.field = x You have to have access to the field to do this
  2. field = x You have to have access to the field to do this. You also can't have another field in the child or only the child's will be set.
  3. setParentField(x) I'd say this is the second best way to do it.
  4. x = callChildMethod() this code can be in the parent. The child has the implementation that returns the result. If this is possible, it's the best way to do it. See the template method pattern
Share:
44,217
IBOED2
Author by

IBOED2

Updated on July 05, 2022

Comments

  • IBOED2
    IBOED2 almost 2 years

    I've found that I can do it this way in the child class:

    ParentClass.variable = value;
    

    But I've been told that it's better practice to use get/set methods and not give direct access to variables outside a class. Though this was for when I had an instance of the class in another class, not for subclasses and superclasses.

    So is there a better way of doing this, and which way is generally considered best practice?