首页 > 代码库 > 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