当前位置: 移动技术网 > IT编程>脚本编程>Ruby > Ruby中的public、private、protected区别小结

Ruby中的public、private、protected区别小结

2017年12月08日  | 移动技术网IT编程  | 我要评论
重点关注private与protected public 默认即为public,全局都可以访问,这个不解释 private c++, “private” 意为 “p

重点关注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"
 end
end
 
class 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
 end
end
 
class c
 def test
  a = a.new
  #a.protected_mth     #wrong
  #a.private_mth      #wrong
 end
end
 
a.new.test
b.new.test
c.new.test


注:ruby的访问控制不同于java,没有包的区别。
其它包中的类只要引用目标类,和目标类同包下类访问控制规则相同。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网