免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3067 | 回复: 4
打印 上一主题 下一主题

Ruby笔记三(类、对象、属性) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-02-19 19:48 |只看该作者 |倒序浏览
Ruby笔记三(类、对象、属性)
  1. class Person
  2.   #initialize是初始化方法,相当于Java的构造器。参数age有一个缺省值18,
  3.   #可以在任何方法内使用缺省参数,而不仅仅是initialize。如果有缺省参数,参数表必须以有缺省值的参数结   
  4.   def initialize( name, age=18 )
  5.     @name = name
  6.     @age = age
  7.     @motherland = "China"
  8.   end #初始化方法结束
  9.   
  10.   def talk
  11.     puts "my name is "+@name+", age is "+@age.to_s  #@age.to_s:将数@age转换为字符串。
  12.     if @motherland == "China"
  13.       puts "I am a Chinese."
  14.     else
  15.       puts "I am a foreigner."
  16.     end
  17.   end # talk方法结束
  18.   attr_writer :motherland
  19. =begin
  20. attr_writer :motherland 相当于
  21. def motherland=(value)
  22.   return @motherland =value
  23. end

  24. attr_ reader :motherland 相当于
  25. def motherland
  26.   return @motherland
  27. end  

  28. attr_accessor :motherland 相当于
  29. attr_reader:motherland;attr_writer :motherland
  30. =end  
  31. end # Person类结束

  32. class Student < Person
  33.   def talk
  34.     puts "I am a student. my name is "+@name+", age is "+@age.to_s
  35.   end # talk方法结束
  36. end # Student类结束

  37. p1=Person.new("kaichuan",20)
  38. p1.talk #my name is kaichuan, age is 20 I am a Chinese.

  39. p2=Person.new("Ben")
  40. p2.motherland="ABC"
  41. p2.talk #my name is Ben, age is 18 I am a foreigner.
  42. p3=Student.new("kaichuan",25)
  43. p3.talk #I am a student. my name is kaichuan, age is 25

  44. p4=Student.new("Ben")
  45. p4.talk #I am a student. my name is Ben, age is 18
  46. 复制代码
复制代码

论坛徽章:
0
2 [报告]
发表于 2012-02-19 19:48 |只看该作者
谢谢分享

论坛徽章:
3
寅虎
日期:2013-11-27 07:53:29申猴
日期:2014-09-12 09:24:152015年迎新春徽章
日期:2015-03-04 09:48:31
3 [报告]
发表于 2012-02-20 11:04 |只看该作者
提示: 作者被禁止或删除 内容自动屏蔽

论坛徽章:
0
4 [报告]
发表于 2012-02-21 07:30 |只看该作者
类成员变量散落在各个方法里,很难看出这个类封装了什么东西 

论坛徽章:
3
寅虎
日期:2013-11-27 07:53:29申猴
日期:2014-09-12 09:24:152015年迎新春徽章
日期:2015-03-04 09:48:31
5 [报告]
发表于 2012-02-21 09:36 |只看该作者
提示: 作者被禁止或删除 内容自动屏蔽
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP