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

目录
相关文章
|
2月前
|
Ruby
|
2月前
|
Ruby
|
2月前
|
Ruby
|
2月前
|
Ruby
|
2月前
|
Ruby
|
2月前
|
Ruby
|
2月前
|
Ruby
|
2月前
|
Ruby
|
Java 程序员 数据安全/隐私保护
【Ruby高级技术】对面向对象里的控制访问,包括类的继承类常量的深入理解和使用
【Ruby高级技术】对面向对象里的控制访问,包括类的继承类常量的深入理解和使用
106 1
|
存储 Ruby
Ruby Programming | 连载 10 - Ruby 的类
Ruby Programming | 连载 10 - Ruby 的类