Changing the value of instance variables of a superclass from a subclass

I found that I can do it this way in a child class:

ParentClass.variable = value; 

But I was told that it is better to use get / set methods and not provide direct access to variables outside the class. Although this was when I had an instance of the class in another class, and not for subclasses and superclasses.

So, is there a better way to do this, and which method is usually considered best practice?

+6
source share
5 answers

You have many options.

  • super.field = x You must have access to the field to do this
  • field = x For this you must have access to the field. You also cannot have another field in the child or only the child will be set.
  • setParentField(x) I would say that this is the second best way to do this.
  • x = callChildMethod() this code may be in the parent. The child has an implementation that returns a result. If possible, this is the best way to do this. See Template Template Template
+3
source

For example, variables that you can make in a subclass method can be done as follows:

 this.variable = value; 

which is great. To change instances of other classes, it is best to use getters and setters.

Indeed, you should prevent other classes from modifying instance variables directly; in this case, getters and setters are best used. But in a subclass, you can directly modify instance variables.

0
source

It is best to use getters and setters. More info.

you can use

 ParentClass.variable = value; 

The best solution depends on the requirement.

0
source

If there is any private member in the superclass, then the setter and getter methods are used, because we cannot use the private member in its subclass.

And in the case of any static instance member, you can directly use it with the class name. If it is a member of an instance of a superclass, try accessing / modifying this element in a subclass using the super keyword. Can you change with the this keyword also if you have an instance member in a superclass and subclass with the same name? Then, in this case, using this JVM keyword, you will access the current member of the instance of the ie class of the subclass.

0
source

one of the principles of OOP is encapsulations , in order to have best practice code and have private members / variables, and then access them using seters / getters - this is a way to provide encapsulation .

-1
source

Source: https://habr.com/ru/post/956968/


All Articles