`
bollaxu
  • 浏览: 217387 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Ruby类的public, protected和private访问控制

    博客分类:
  • Ruby
 
阅读更多

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"
    end
end

class 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
    end
end

a = ClassChild.new
puts a.attr1
a.callProtected
a.callPrivate #private method is also inherited
#a.privateMethod #fail
#a.protectedMethod #fail

a.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不行

 

欢迎指正!

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics