Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Oop 为什么角色是继承错误之一?_Oop_Inheritance_Composition - Fatal编程技术网

Oop 为什么角色是继承错误之一?

Oop 为什么角色是继承错误之一?,oop,inheritance,composition,Oop,Inheritance,Composition,下面的插图摘自我的演讲幻灯片。我使用组合和继承来编写一个学生-人类,我认为它们都很合理 (我知道如果一个人可以拥有多个职位——1:n,那么继承就不起作用,所以我只选择了1人:2职位关系) 使用继承的代码: class Person attr_accessor :name, :gender, :height, :weight def initialize(name, gender, height, weight) @name = name @gen

下面的插图摘自我的演讲幻灯片。我使用组合和继承来编写一个
学生-人
类,我认为它们都很合理

(我知道如果一个人可以拥有多个职位——1:n,那么继承就不起作用,所以我只选择了1人:2职位关系)

使用继承的代码:

class Person
    attr_accessor :name, :gender, :height, :weight
    def initialize(name, gender, height, weight)
        @name = name
        @gender = gender
        @height = height
        @weight = weight
    end
    def cry
        "woooo"
    end
end


class Student < Person
    attr_accessor :student_id
    def initialize(name, gender, height, weight, student_id)
        super(name, gender, height, weight)
        @student_id = student_id
    end
    def study
        "Student #{name} with #{student_id} is studying now"
    end
end

s = Student.new("Lin", "Male", 173, 75, 666777)
puts s.cry()
puts s.study
我发现使用作文的代码有一个不好的方面,我不能让学生叫他的名字。我的意思是,我不能让study()方法像继承代码那样返回:

"Student #{name} with #{student_id} is studying now"

如果有人既是研究生又是导师呢?那个人是如何被描绘成一个物体的?@Patashu你是100%正确的。但在第二段中,我声明,在这种情况下,我只取1:1,
"Student #{name} with #{student_id} is studying now"