0
0

More than 1 year has passed since last update.

【Ruby】メソッドのオーバーライド

Last updated at Posted at 2021-11-30

メソッドのオーバーライド

親クラスを継承した子クラスで同じメソッドを定義するとメソッドがオーバーライドされる。

class Parent
  def talk
    puts '早く寝なさい'
  end
end

class Child < Parent
  def talk
    puts '眠い'
  end
end

p = Parent.new
p.talk
#=> 早く寝なさい

p = Child.new
p.talk
#=> 眠い

super

オーバーライドされる前のメソッドを呼び出すことができるメソッド。
superで親クラスのtalkメソッドを呼び出している。

class Parent
  def talk
    puts '早く寝なさい'
  end
end

class Child < Parent
  def talk
    super
    puts '眠い'
  end
end

p.talk
#=> 早く寝なさい
#=> 眠い

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0