サブクラス
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 Catsuperclass はクラスの親を示します。Ruby のクラスにはスーパークラスがちょうど 1 つあり、< なしで宣言されたクラスは Object を継承します。これにより、すべてのオブジェクトに to_s や inspect などのメソッドが与えられます。
class Animal
end
class Dog < Animal
end
puts Dog.superclass
puts Animal.superclass
puts Object.superclass出力:
Animal
Object
BasicObject継承はis-a関係に当てはまります。犬は動物であり、普通預金口座は口座です。共有する振る舞いはスーパークラスに一度だけ記述し、それぞれのサブクラスでは異なる部分を追加します。このセクションでは各クラスがそれぞれ独自のファイルにあり、スーパークラスのファイルが最初に読み込まれます:
# main.rb
require_relative 'animal' # まずスーパークラスを
require_relative 'dog' # class Dog < Animal には Animal が必要
require_relative 'cat'チャレンジ
簡単クラスを完成させてください。Vehicle は name と wheels の数を保持し、Mini has 4 wheels を返す describe を持ちます。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
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
オブジェクト指向プログラミングのすべてのレッスン
自分で練習してみよう: Rubyオンラインコンパイラ