`
凌川__
  • 浏览: 82281 次
  • 性别: Icon_minigender_1
最近访客 更多访客>>
社区版块
存档分类
最新评论

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    
 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics