Menu
CoddyTech

继承与重写

Coddy 面向 Dart 开发者的 Ruby 课程 课程的第 32 课,共 48 课。

Dart 类和 Ruby 类都只有一个父类,mixin 或模块可以为它们添加其他行为。Dart 普通实例方法可以被重写,而 @override 用于向工具说明这一意图。Ruby 不需要这个注解。移植后请验证方法的行为,不要仅凭名称相同就认为行为一致。

Dart:完整程序

class Bird {String sound()=>"chirp";}
class Owl extends Bird {@override String sound()=>"hoot";}
void main() {
print(Bird().sound());print(Owl().sound());
}

Ruby:完整程序

class Bird
  def sound; "chirp"; end
end
class Owl < Bird
  def sound; "hoot"; end
end
puts Bird.new.sound
puts Owl.new.sound
challenge icon

挑战

简单

定义 Fee#cost(units),使其返回 units*2。DiscountFee 继承 Fee 并重写 cost,使其返回 units(所有 units 均为非负数)。solve 读取 base 或 discount,后面跟着 units;然后创建对应类型的对象。

让 solve(input) 返回文本,不要打印。锁定的驱动程序会打印返回的文本,并在末尾添加一个换行符,还会独立检查必需的公共 API。

你的代码写在 exercise.rb、fee.rb 和 discount_fee.rb 中。main.rb 包含提供的输入/输出代码,不能编辑。

亲手试试

require_relative 'exercise'
require_relative 'fee'
require_relative 'discount_fee'
def check(value)
  raise 'Public API check failed' unless value
end
check(DiscountFee.new.is_a?(Fee))
check(Fee.new.cost(7) == 14 && DiscountFee.new.cost(7) == 7)

puts solve(STDIN.read)
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Dart 开发者的 Ruby 课程中的所有课

自己练习: Ruby 在线编译器