Menu
CoddyTech

继承与重写

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

Kotlin 中的类和成员默认是 final,要进行重写,需要使用 open 或其他合适的声明。Ruby 的普通方法无需这些修饰符,就能参与动态查找。两种语言都使用一个类作为父类,接口或模块则可以添加其他行为。翻译这些声明后,请验证重写是否符合预期。

Kotlin:完整程序

open class Bird {open fun sound()="chirp"}
class Owl:Bird(){override fun sound()="hoot"}
fun main(){
println(Bird().sound());println(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(所有单位数均为非负数)。solve 读取 base 或 discount,后面跟着单位数;创建对应类型的对象。

让 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自我测试

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

面向 Kotlin 开发者的 Ruby中的所有课

自己练习: Ruby 在线编译器