Changing the value of superclass instance variable

2019-04-07 06:36发布

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?

5条回答
再贱就再见
2楼-- · 2019-04-07 07:24

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楼-- · 2019-04-07 07:26

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 .

查看更多
The star\"
4楼-- · 2019-04-07 07:27

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

you can use,

ParentClass.variable = value;

The best soltion depends on the requirement.

查看更多
手持菜刀,她持情操
5楼-- · 2019-04-07 07:31

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
查看更多
Evening l夕情丶
6楼-- · 2019-04-07 07:34

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.

查看更多
登录 后发表回答