Changing the value of superclass instance variables from a subclass

IBOED2 picture IBOED2 · Oct 29, 2013 · Viewed 39.1k times · Source

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?

Answer

Daniel Kaplan picture Daniel Kaplan · Oct 29, 2013

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