class Student < Person

方长卿
2023-12-01
# encoding: utf-8
#E4.4-1.rb ,接着上一节的代码,添加如下:
class Person
def initialize( name, age=18 )
@name = name
@age = age
@motherland = "China"
end #初始化方法结束
def talk
puts "my name is "+@name+", age is "+@age.to_s
if @motherland == "China"
puts "I am a Chinese."
else
puts "I am a foreigner."
end
end # talk方法结束
attr_writer :motherland
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类结束

p3=Student.new("kaichuan",25); p3.talk
p4=Student.new("Ben"); p4.talk

=begin
I am a student. my name is kaichuan, age is 25
I am a student. my name is Ben, age is 18
请按任意键继续. . .
=end

 类似资料: