sub class 中是否可以访问 Ruby 私有方法?
Is Ruby private method accessible in sub class?
我的代码如下:
class A
private
def p_method
puts "I'm a private method from A"
end
end
class B < A
def some_method
p_method
end
end
b = B.new
b.p_method # => Error: Private method can not be called
b.some_method # => I'm a private method from A
b.some_method
调用在 class A
中定义的私有方法。如何在继承它的 class 中访问私有方法?这种行为在所有面向对象的编程语言中都一样吗? Ruby如何封装?
这里是this source的简要解释:
- Public methods can be called by anyone---there is no access control. Methods are public by default (except for initialize, which is always private).
- Protected methods can be invoked only by objects of the defining class and its subclasses. Access is kept within the family.
- Private methods cannot be called with an explicit receiver. Because you cannot specify an object when using them, private methods can be called only in the defining class and by direct descendants within that same object.
来自类似问题的此答案更详细地扩展了该主题:
我的代码如下:
class A
private
def p_method
puts "I'm a private method from A"
end
end
class B < A
def some_method
p_method
end
end
b = B.new
b.p_method # => Error: Private method can not be called
b.some_method # => I'm a private method from A
b.some_method
调用在 class A
中定义的私有方法。如何在继承它的 class 中访问私有方法?这种行为在所有面向对象的编程语言中都一样吗? Ruby如何封装?
这里是this source的简要解释:
- Public methods can be called by anyone---there is no access control. Methods are public by default (except for initialize, which is always private).
- Protected methods can be invoked only by objects of the defining class and its subclasses. Access is kept within the family.
- Private methods cannot be called with an explicit receiver. Because you cannot specify an object when using them, private methods can be called only in the defining class and by direct descendants within that same object.
来自类似问题的此答案更详细地扩展了该主题: