Ruby - 如何处理子类意外覆盖父类(super class)私有(private)字段的问题?

标签 ruby oop subclass subclassing

假设您编写了一个类 Sup,我决定将其扩展为 Sub <Sup。我不仅需要了解你发布的接口(interface),还需要了解你的私有(private)字段。见证这次失败:

class Sup

  def initialize
    @privateField = "from sup"
  end

  def getX
    return @privateField
  end
end

class Sub < Sup

  def initialize
    super()
    @privateField = "i really hope Sup does not use this field"
  end
end

obj = Sub.new
print obj.getX #  prints "i really hope Sup does not use this field"

问题是,解决这个问题的正确方法是什么?看起来子类应该能够使用它想要的任何字段而不会弄乱父类(super class)。

编辑:equivalent example in Java返回 "from Sup",这也是它应该产生的答案。

最佳答案

实例变量与继承无关,它们是在第一次使用时创建的,而不是通过某种定义机制创建的,因此在语言中对它们没有特殊的访问控制,它们不能被隐藏。

Not only do I need to understand your published interface, but I also need to understand your private fields.

实际上这是一个“官方”职位。摘自“The Ruby Programming Language”一书(其中 Matz 是作者之一):

... this is another reason why it is only safe to extend Ruby classes when you are familiar with (and in control of) the implementation of the superclass.

如果您对它的内在和外在都一无所知,那您就只能靠自己了。悲伤但真实。

关于Ruby - 如何处理子类意外覆盖父类(super class)私有(private)字段的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5352963/

相关文章:

php - 检查函数是否已经被调用

c++ - 我需要一些 C++ 专家关于扩展 std::string 的意见

java - 从 Java 中的子类构造函数调用父类(super class)

python - PySide:容器类中 QGraphicsView 的事件过滤器

ruby - 是什么启发了 Ruby 的 =begin .. =end 注释 block 语法?

Swift 4 : type(of:self). 描述()与字符串(描述:类型(of:self))不同

ruby-on-rails - ORM 如何将类/属性与​​表/字段相关联?

java - 一个类怎么会有自己类型的成员,这不是无限递归吗?

ruby - 无需 Chef 或 Knife 从 metadata.rb 生成 metadata.json

ruby - 使用 Gems 时尾随 UTF-8 八位字节无效