0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have 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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?