Changing the value of superclass instance variables from a subclass

泪湿孤枕 提交于 2019-12-09 17:01:05

问题


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?


回答1:


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



回答2:


For instance variables you can do the following in a method of a subclass:

this.variable = value;

which is perfectly fine. To modify instances of other classes it's best to use getters and setters.

It's indeed true that you should prevent other classes from modifying instance variables directly; in that case it's best to use getters and setters. But in a subclass you can modify instance variables directly.




回答3:


You best practice is to use getters and setters. More INFO.

you can use,

ParentClass.variable = value;

The best soltion depends on the requirement.




回答4:


If there are any private member in the superclass then there is a use of setter and getter method as because we cannot use private member in its subclass.

And in case of any static instance member you can directly use with the help of class name. If it is a instance member of the super class then try to access / modify that member in the subclass with the use of super keyword. You can modify with the help of this keyword also what if you are having instance member in superclass and subclass with the same name? Then in this case, with the use of this keyword JVM will access the current class instance member i.e subclass member.




回答5:


one of OOP principles is encapsulations to have best practice code , and having a private members/variables , then access them using setters/getters is the way to achieve encapsulation .



来源:https://stackoverflow.com/questions/19666652/changing-the-value-of-superclass-instance-variables-from-a-subclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!