[英]Is it possible to access the protected methods outside the class - ruby
class User
def say_secret_with_self
self.secret
end
protected
def secret
"secret"
end
end
u = User.new
p u.say_secret_with_self # => "secret"
I have heard that protected methods can be accessed only by inherited members. 我听说受保护的方法只能由继承的成员访问。 But the above is possible in ruby.
但是以上是可能的红宝石。 Is it correct code?
它是正确的代码吗?
Yes it is correct code. 是的,它是正确的代码。 An instance of the class is able to call self methods even if they are
protected
. 该类的实例即使已
protected
也可以调用self方法。 protected/private
methods are hidden from the outside but not from inside. protected/private
方法是从外部隐藏的,而不是从内部隐藏的。
the method secret
is still protected. 该方法的
secret
仍然受到保护。 you cant call it from outside of your class (or inherited class). 您不能从您的班级(或继承的班级)外部调用它。 but you can call it from
say_secret_with_self
because it is still in the same class with secret
但您可以从
say_secret_with_self
调用它,因为它仍然与secret
属于同一类
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.