Ruby类的public, protected和private访问控制
Ruby类下对访问控制的限制也是用public,protected和private来做的。虽然用的是和C++和Java相同的名字,但是Ruby下的protected和private定义还是有所不同的。
?
class ClassSuper attr_accessor :attr1 def initialize @attr1 = "attr1" end private def privateMethod puts "this is private" end #protected = private which cannot be called directly protected def protectedMethod puts "this is protected" endendclass ClassChild < ClassSuper public def callProtected protectedMethod end def callPrivate privateMethod end def objProtected obj obj.protectedMethod end #this is invalid def objPrivate obj obj.privateMethod endenda = ClassChild.newputs a.attr1a.callProtecteda.callPrivate #private method is also inherited#a.privateMethod #fail#a.protectedMethod #faila.objProtected a#a.objPrivate a #this is the difference between protected and private
?总结一下,Ruby的不同之处在于:
1. 父类的的private和protected都可以被子类所继承
2. protected和private一样不能被显式调用
3. protected和private的区别是protected可以在类的其他方法中以实例形式调用(如: obj.protectedMethod),而private不行
?
欢迎指正!