publicclass:Ruby 的 class 中的 private、 protected、public

Private
private 只能 在本类和子类 上下文中且只能通过self访问
这个意思就是:private只能在本对象内部访问到
对象例子变量(@)访问权限就是 private
复制代码 代码如下:

AccessTest
def test
“test private”
end
def test_other(other)
“other object ”+ other.test
end
end
t1 = AccessTest.
t2 = AccessTest.
p t1.test # => test private
p t1.test_other(t2) # => other object test private

# Now make 'test' private
AccessTest
private :test
end


p t1.test_other(t2) # in `test_other': private method `test' called for #<AccessTest:0x292c14> (NoMethodError)

Protected
protect 只能 在本类和子类 上下文中但可以使用 other_object.function形式(这跟 C private 模式等同)
这个关键是 protected可以在同类(含子类)其它对象内部中使用
# Now make 'test' protect
AccessTest
protected:test
end
p t1.test_other(t2) # other object test private
Public
public 可以在任何地方成员和常量默认访问权限就是public
Tags:  publicclass

延伸阅读

最新评论

发表评论