凝望长空 发表于 2012-02-19 19:48

Ruby笔记三(类、对象、属性)

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
复制代码

小鬼萌萌控 发表于 2012-02-19 19:48

谢谢分享

Sevk 发表于 2012-02-20 11:04

yakczh 发表于 2012-02-21 07:30

类成员变量散落在各个方法里,很难看出这个类封装了什么东西 

Sevk 发表于 2012-02-21 09:36

页: [1]
查看完整版本: Ruby笔记三(类、对象、属性)