Changing the value of superclass instance variables from a subclass

▼魔方 西西 提交于 2019-12-04 04:03:27

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

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.

Isuru Gunawardana

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

you can use,

ParentClass.variable = value;

The best soltion depends on the requirement.

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.

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 .

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