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    
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值