4.3 封裝

讓我們來定義一個類,類名是Person,類名首字母要大寫;屬性有姓名@name、年齡@age、國籍@motherland,實例變量用@開頭; 方法有一個,叫talk, 方法名和參數名應該用一個小寫字母開頭或者用一個下劃線開頭,看程序 E4.3-1.rb 。#=>my name is kaichuan, age is 20
  I am a Chinese.
  my name is Ben, age is 18
  I am a foreigner.
@age.to_s的含義是:將數@age轉換爲字符串。
initialize是初始化方法,相當於Java的構造器。參數age有一個缺省值18,可以在任何方法內使用缺省參數,而不僅僅是initialize。如果有缺省參數,參數表必須以有缺省值的參數結尾。
 

ruby 代碼
  1. class  Person   
  2.   def  initialize( name, age=18 )   
  3.     @name = name   
  4.     @age = age   
  5.     @motherland = "China"  
  6.   end  #初始化方法結束    
  7.   def  talk   
  8.     puts "my name is "+@name+", age is "+@age.to_s   
  9.     if  @motherland == "China"  
  10.       puts "I am a Chinese."  
  11.     else  
  12.       puts "I am a foreigner."  
  13.     end  
  14.   end  # talk方法結束   
  15.   attr_writer :motherland  
  16. end   # Person類結束   
  17. p1=Person.new("kaichuan",20)   
  18. p1.talk   
  19. p2=Person.new("Ben")   
  20. p2.motherland="ABC"  
  21. p2.talk  

 

attr_writer :motherland 相當於
def motherland=(value)
  return @motherland =value
end 
attr_ reader :motherland 相當於
def motherland
  return @motherland
end 

這就是我們熟悉的getter 和setter 方法的簡寫形式。你不熟悉也不重要。
attr_accessor :motherland 相當於attr_reader:motherland; attr_writer :motherland
這個Person類可以talk,如何實現的?寫Person類的人知道,其它的類不知道,只是調用而已。封裝完成了隱藏實現。

完整閱讀,請看我寫的 Ruby語言中文教程all in one    
 

發佈了0 篇原創文章 · 獲贊 0 · 訪問量 585
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章