- 论坛徽章:
- 0
|
Ruby笔记三(类、对象、属性) - class Person
- #initialize是初始化方法,相当于Java的构造器。参数age有一个缺省值18,
- #可以在任何方法内使用缺省参数,而不仅仅是initialize。如果有缺省参数,参数表必须以有缺省值的参数结
- def initialize( name, age=18 )
- @name = name
- @age = age
- @motherland = "China"
- end #初始化方法结束
-
- def talk
- puts "my name is "+@name+", age is "+@age.to_s #@age.to_s:将数@age转换为字符串。
- if @motherland == "China"
- puts "I am a Chinese."
- else
- puts "I am a foreigner."
- end
- end # talk方法结束
- attr_writer :motherland
- =begin
- attr_writer :motherland 相当于
- def motherland=(value)
- return @motherland =value
- end
- attr_ reader :motherland 相当于
- def motherland
- return @motherland
- end
- attr_accessor :motherland 相当于
- attr_reader:motherland;attr_writer :motherland
- =end
- end # Person类结束
- class Student < Person
- def talk
- puts "I am a student. my name is "+@name+", age is "+@age.to_s
- end # talk方法结束
- end # Student类结束
- p1=Person.new("kaichuan",20)
- p1.talk #my name is kaichuan, age is 20 I am a Chinese.
- p2=Person.new("Ben")
- p2.motherland="ABC"
- p2.talk #my name is Ben, age is 18 I am a foreigner.
- p3=Student.new("kaichuan",25)
- p3.talk #I am a student. my name is kaichuan, age is 25
- p4=Student.new("Ben")
- p4.talk #I am a student. my name is Ben, age is 18
- 复制代码
复制代码 |
|