从子类更改超类实例变量的值 [英] Changing the value of superclass instance variables from a subclass

查看:161
本文介绍了从子类更改超类实例变量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现我可以在子类中这样做:

I've found that I can do it this way in the child class:

ParentClass.variable = value;

但我被告知最好使用get / set方法而不是直接访问对类外的变量。虽然这是因为我在另一个类中有一个类的实例,而不是子类和超类。

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. super.field = x 您必须有权访问该字段才能执行这

  2. field = x 您必须有权访问该字段才能执行此操作。您也不能在孩子身上再设置字段,否则只会设置孩子。

  3. setParentField (x)我认为这是第二种最佳方式。

  4. x = callChildMethod()此代码可以在父代。子进程具有返回结果的实现。如果这是可能的,那么这是最好的方法。请参阅模板方法模式

  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

这篇关于从子类更改超类实例变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆