首页 > 代码库 > RUBY的类封装,继承,多态简单演示
RUBY的类封装,继承,多态简单演示
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 China." else puts "I am a foreigner." end end attr_writer:motherland end p1=Person.new("Kaichuan",20) p1.talk p2=Person.new("Ben") p2.motherland="ABC" p2.talk class Student < Person def talk puts "I am a student. my name is " +@name+",age is " +@age.to_s end end p3=Student.new("Chengang","25"); p3.talk p4=Student.new("Ben"); p4.talk class Worker < Person def talk puts "I am a worker. my name is " +@name +",age is " + @age.to_s end end p5=Worker.new("Hiong",30) p5.talk p6=Worker.new("Ben") p6.talk 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 China." else puts "I am a foreigner." end end attr_writer:motherland end p1=Person.new("Kaichuan",20) p1.talk p2=Person.new("Ben") p2.motherland="ABC" p2.talk class Student < Person def talk puts "I am a student. my name is " +@name+",age is " +@age.to_s end end p3=Student.new("Chengang","25"); p3.talk p4=Student.new("Ben"); p4.talk class Worker < Person def talk puts "I am a worker. my name is " +@name +",age is " + @age.to_s end end p5=Worker.new("Hiong",30) p5.talk p6=Worker.new("Ben") p6.talk
>ruby hello.rb
my name is Kaichuan,age is 20
I am a China.
my name is Ben,age is 18
I am a foreigner.
I am a student. my name is Chengang,age is 25
I am a student. my name is Ben,age is 18
I am a worker. my name is Hiong,age is 30
I am a worker. my name is Ben,age is 18
>Exit code: 0
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。