Menu
CoddyTech

子类

本课属于 Coddy Ruby 学习旅程的“面向对象编程”单元。第 22 课,共 57 课。

继承基于现有类创建新类。class Dog < Animal 会让 Dog 成为 Animal 的子类,而 Animal 是它的超类。狗拥有动物的所有方法,包括 initialize,以及 Dog 添加的方法:

class Animal
  attr_reader :name

  def initialize(name)
    @name = name
  end

  def eat
    "#{name} is eating"
  end
end

class Dog < Animal
  def fetch
    "#{name} fetches the ball"
  end
end

rex = Dog.new("Rex")
puts rex.eat
puts rex.fetch

输出:

Rex is eating
Rex fetches the ball

新增的方法只属于子类。普通的 Animal 没有这些方法,同级类(例如 Cat)也无法使用 Dog 的方法:

class Animal
  def breathe
    "breathing"
  end
end

class Dog < Animal
  def fetch
    "fetching"
  end
end

class Cat < Animal
end

puts Cat.new.breathe
begin
  Cat.new.fetch
rescue NoMethodError => e
  puts e.message
end

输出:

breathing
undefined method `fetch' for an instance of Cat

superclass表示类的父类。Ruby 类只有一个父类,不带 < 声明的类会继承自 Object,因此每个对象都具有 to_s 和 inspect 等方法:

class Animal
end

class Dog < Animal
end

puts Dog.superclass
puts Animal.superclass
puts Object.superclass

输出:

Animal
Object
BasicObject

继承适用于“是一个”的关系:狗是动物,储蓄账户是账户。共享的行为只需在超类中定义一次,每个子类再添加各自不同的内容。在这个单元中,每个类都位于自己的文件中,并且会先加载超类所在的文件:

# main.rb
require_relative 'animal'   # 先加载父类
require_relative 'dog'      # 类 Dog < Animal 需要先加载 Animal
require_relative 'cat'
challenge icon

挑战

简单

补全这些类。Vehicle 用于存储 name 和 wheels 的数量,并包含 describe,它会返回 Mini has 4 wheels。Car 和 Bike 是 Vehicle 的子类,它们不定义 initialize。Car 添加了 honk,返回 Mini says beep;Bike 添加了 ring,返回 BMX rings。

提供的代码会读取 car Mini 或 bike BMX 这样的行,创建一个有 4 个轮子的 Car 或一个有 2 个轮子的 Bike,并输出 describe 的结果、声音(honk 或 ring),以及该对象所属类的父类。

你的代码要写在 vehicle.rb、car.rb 和 bike.rb 中。main.rb 包含提供的输入/输出代码,不能编辑。

亲手试试

require_relative 'vehicle'
require_relative 'car'
require_relative 'bike'

# 提供的输入输出代码:保持原样。
input = []
while (line = gets)
  input << line.chomp
end
input.each do |line|
  kind, name = line.split(" ", 2)
  if kind == "car"
    v = Car.new(name, 4)
    sound = v.honk
  else
    v = Bike.new(name, 2)
    sound = v.ring
  end
  puts v.describe
  puts sound
  puts v.class.superclass
end
quiz icon自我测试

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

面向对象编程中的所有课

自己练习: Ruby 在线编译器