我有如下代码:
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
调用类 A
中定义的私有(private)方法。如何在继承它的类中访问私有(private)方法?这种行为在所有面向对象的编程语言中都一样吗? 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.
这个来自类似问题的答案更详细地扩展了该主题:https://stackoverflow.com/a/1565640/814591
关于ruby - 子类中是否可以访问 Ruby 私有(private)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31217588/