細說Ruby裏的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
end

test=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
  
end

test = Test.new
test.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
end

class SonTest < Test
  def access_method
    puts method_public
    puts method_protected    
    puts method_private
  end
end

test = SonTest.new
test.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
  
end

test1 = Test.new
test2 = 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方法。


以上的陳述中,請注意“調用”和“訪問”的區別。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章