细说Ruby里的public、protected和private

来源:互联网 发布:如何成为算法工程师 编辑:程序博客网 时间:2024/04/28 14:59
首先来看这段代码:
class Test      def method_public    puts  "In method_public"      end     def method_protected    puts "In method_protected"       end     def method_private    puts "In method_private"     end   protected :method_protected  private   :method_privateendtest=Test.new

分别尝试:

        test.method_public
        输出:In method_public

        test.method_protected
        输出:test.rb:20: protected method `method_protected' called for #<Test:0x3756068> (NoMethodError)

        test.method_private

        输出:test.rb:21: private method `method_private' called for #<Test:0x346070> (NoMethodError)

可知:public能被实例对象调用,protected和private不能被实例对象直接调用。

改写代码:

class Test      def method_public    puts  "In method_public"   end    def method_protected    puts "In method_protected"       end      def method_private    puts "In method_private"     end   protected :method_protected  private     :method_private    def access_method    puts method_public    puts method_protected        puts method_private  end  endtest = Test.newtest.access_method
        输出:

        In method_public
        nil
        In method_protected
        nil
        In method_private
        nil

可知:三种方式都能被定义它们的类访问。

改写代码:

class Test      def method_public    puts  "In method_public"   end    def method_protected    puts "In method_protected"       end      def method_private    puts "In method_private"     end   protected :method_protected  private   :method_privateendclass SonTest < Test  def access_method    puts method_public    puts method_protected        puts method_private  endendtest = SonTest.newtest.access_method
        输出:

       In method_public
       nil
       In method_protected
       nil
       In method_private
       nil
可知:三种方法都能被定义它们的类的子类访问。

改写代码:

class Test      def method_public    puts  "In method_public"   end    def method_protected    puts "In method_protected"       end      def method_private    puts "In method_private"     end   protected :method_protected  private   :method_private    def call_method_protected(testmember)    puts testmember.method_protected  end  def call_method_private(testmember)    puts testmember.method_private  end  endtest1 = Test.newtest2 = Test.new
分别尝试:

       test2.call_method_protected(test1)

       输出:

       In method_protected
       nil

       test2.call_method_private(test1)

       输出:test.rb:21:in `call_method_private': private method `method_private' called for #<Test:0x36c5af4> (NoMethodError)

可知:protected方法可以被其他的实例对象访问,而private方法只能被自己的实例对象访问。


总结一下


public方法可以被定义它的类子类访问,并可以被类和子类的实例对象调用;

protected方法可以被定义它的类子类访问,不能被类和子类的实例对象调用,但可以被该类的实例对象(所有)访问;

private方法可以被定义它的类子类访问,不能被类和子类的实例对象调用,且实例对象只能访问自己的private方法。


以上的陈述中,请注意“调用”和“访问”的区别。

0 0
原创粉丝点击