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 1 year has passed since last update.

【オブジェクト指向】ポリモーフィズム

Posted at

##ポリモーフィズムとは
意味:多相性、多態性

プログラミング言語の持つ性質の一つで、ある関数やメソッドなどが、引数や返り値の数やデータ型などの異なる複数の実装を持ち、呼び出し時に使い分けるようにできること。
多態性の概念がない言語では、同名のプログラムが二重に定義されていますとエラーが出てくる。

  • dogもcatも同じcryメソッドを呼び出しているが、呼び出し先に応じて適切なメソッドを実行している。
class Animal
  attr_accessor :name

  def cry(voice='')
    "#{self.name}: #{voice}"
  end
end

class Dog < Animal
  def cry(voice='わんわん')
    super
  end
end

class Cat < Animal 
  def cry (voice='にゃー')
    super
  end
end

dog = Dog.new
dog.name = 'チョコ'

cat = Cat.new
cat.name = 'ミケ'

dog.cry     
#=>チョコ: わんわん
cat.cry     
#=>ミケ:   にゃーにゃー
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?