假设您编写了一个类 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/