Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the value of superclass instance variables from a subclass

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?

like image 587
IBOED2 Avatar asked Oct 29 '13 18:10

IBOED2


1 Answers

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
like image 161
Daniel Kaplan Avatar answered Oct 21 '22 16:10

Daniel Kaplan