LoginSignup
0
0

More than 1 year has passed since last update.

継承について理解したい!

Last updated at Posted at 2021-05-09

はじめに

皆さんは、「継承」を使いこなせていますでしょうか?
開発において使わないことはないのですはないか、というくらいに頻繁に利用します。
確実に抑えておきたい技術です!

継承について

Rubyは単一継承をサポートしています。
継承された方のクラスをスーパークラス、した方をサブクラスと言います。
サブクラスには、スーパークラスのメソッドが継承されます。

class Parent
  def parent
    puts 'hello parent!'
  end
end

class Child < Parent
  def child
    puts 'hello child!'
  end
end

child = Child.new
child.parent #=>'hello parent!'
child.child #=>'hello child!'

オーバーライド

スーパークラスに定義済みのメソッドを、サブクラスで定義することをオーバーライドという。
オーバーライドすることで、スーパークラスを引き継ぎながら追加で新たな処理を追加できる。

class Parent
  def hello
    puts 'hello parent!'
  end
end

class Child < Parent
  def hello
    super #=> Parent#helloが呼び出される

    puts 'hello child!'
  end
end

child = Child.new
child.hello #=> 'hello parent!' 'hello child!'

スーパークラスを調べるには、クラス名.superclassで取得できる。

Child.superclass #=> Parent

継承されるもの

サブクラスは、スーパークラスのインスタンスメソッド、クラスメソッド、定数を継承します。

class Parent
  PARENAT = 'PARENT'
  def initialize
    @foo = 'foo'
  end
end

class Child < Parent
end

Parent.new #=> #<Parent...@foo="foo">
Child.new #=> #<Child...@foo="foo">

Child::PARENT #=> "PARENT"

終わりに

継承をすることで、リファクタリングにもつながるので正しく利用しましょう!

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