Ruby中访问控制符public,private,protected区别总结

来源:互联网 发布:淘宝图片尺寸和像素 编辑:程序博客网 时间:2024/06/03 14:43

重点关注private与protected

public

默认即为public,全局都可以访问,这个不解释

private

C++, “private” 意为 “private to this class”, 但是Ruby中意为 “private to this instance”.
意思是:C++中,对于类A,只要能访问类A,就能访问A的对象的private方法。
Ruby中,却不行:你只能在你本对象的实例中访问本对象的private方法。
因为Ruby的原则是“private意为你不能指定方法接收者”,接收者只能是self,且self必须省略!
所以Ruby中子类可以访问父类的private方法。但self.private_method是错的。

protected

可以在本类或子类中访问,不能在其它类中访问。

测试代码(public均可访问,代码略)

class A  def test    protected_mth    private_mth    self.protected_mth    #self.private_mth     #wrong    obj = B.new    obj.protected_mth    #obj.private_mth       #wrong  end  protected  def protected_mth    puts "#{self.class}-protected"  end  private  def private_mth    puts "#{self.class}-private"  endendclass B < A  def test    protected_mth    private_mth    self.protected_mth    #self.private_mth     #wrong    obj = B.new    obj.protected_mth    #obj.private_mth       #wrong  endendclass C  def test    a = A.new    #a.protected_mth          #wrong    #a.private_mth            #wrong  endendA.new.testB.new.testC.new.test
参考:http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Classes#Declaring_Visibility
0 0
原创粉丝点击