是否可以将子类的实例变量传递给父类?
我有一个类Borrower
,它由类Student
和类Professor
继承。我想实施一种方法让他们借书。既然借书都是这样的,我想在Borrower
课程中编写方法。我的问题是,儿童班可以借用不同数量的书籍。是否可以将该数字传递给父类(Borrower
)?每个实例的数量会根据Student
或Professor
borrower.rb
class Borrower < Person
attr_reader :id
def initialize(name, surname, id)
super(name, surname)
@books = []
@id = id
end
def books_to_borrow(books)
if books.length <= leftToBorrow
@books = books
else
puts "You can only borrow #{leftToBorrow} books"
return 0
end
end
end
student.rb
class Student < Borrower
attr_reader :studentType
def initialize(name, surname, studentType, id)
super(name, surname, id)
@studentType = studentType #Where studentType is 0 for Bachelors and 1 for Masters.
@leftToBorrow = 5 if @studentType == 1
@leftToBorrow = 4 if @studentType == 0
end
end
professor.rb
class Professor < Borrower
def initialize(name, surname, id)
super(name, surname, id)
@leftToBorrow = 70
end
end
修改
我尝试将我想要的变量添加到Borrower
类,所以现在我可以访问它了。我将其初始化为0,然后孩子改变它的值,所以它也在父母中改变。但是,我仍然认为有更好的方法。
你觉得我的方法有误吗? 谢谢。