- 論壇徽章:
- 0
|
Ruby筆記三(類、對(duì)象、屬性) - class Person
- #initialize是初始化方法,相當(dāng)于Java的構(gòu)造器。參數(shù)age有一個(gè)缺省值18,
- #可以在任何方法內(nèi)使用缺省參數(shù),而不僅僅是initialize。如果有缺省參數(shù),參數(shù)表必須以有缺省值的參數(shù)結(jié)
- def initialize( name, age=18 )
- @name = name
- @age = age
- @motherland = "China"
- end #初始化方法結(jié)束
-
- def talk
- puts "my name is "+@name+", age is "+@age.to_s #@age.to_s:將數(shù)@age轉(zhuǎn)換為字符串。
- if @motherland == "China"
- puts "I am a Chinese."
- else
- puts "I am a foreigner."
- end
- end # talk方法結(jié)束
- attr_writer :motherland
- =begin
- attr_writer :motherland 相當(dāng)于
- def motherland=(value)
- return @motherland =value
- end
- attr_ reader :motherland 相當(dāng)于
- def motherland
- return @motherland
- end
- attr_accessor :motherland 相當(dāng)于
- attr_reader:motherland;attr_writer :motherland
- =end
- end # Person類結(jié)束
- class Student < Person
- def talk
- puts "I am a student. my name is "+@name+", age is "+@age.to_s
- end # talk方法結(jié)束
- end # Student類結(jié)束
- 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
- 復(fù)制代碼
復(fù)制代碼 |
|