1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

クラス継承のメリット

Posted at

Rubyでクラス継承を使うメリットとは?【コード例あり】

こんにちは。
今回は、Rubyにおける「クラスの継承」が持つ実用的なメリットについてまとめてみました。


🎯 結論から言うと

クラスを継承することで、共通機能は親クラスにまとめつつ、
特定の子クラスだけで追加・変更・削除が簡単に行える!


👇 具体例:User クラスと AdminUser クラス

以下のコードを見てください。

class User
  REGION = 'USA'
  @@count = 0

  def initialize(name)
    @name = name
    @@count += 1
  end

  def hello
    puts "Hello! Iam #{@name}. #{@@count} instance(s)"
  end
end

class AdminUser < User
  def hello
    puts 'Admin!!'
  end

  def admin_hello
    puts "Hello! Iam #{@name}. #{@@count} instance(s)"
  end
end

nakamura = AdminUser.new('Nakamura')
nakamura.hello         # => "Admin!!"
nakamura.admin_hello   # => "Hello! Iam Nakamura. 1 instance(s)"

🧩 終わりに

今回の記事は、自分自身がRubyのクラス継承を学ぶ中で
「なるほど、こういうときに使えるのか」と思ったポイントを整理した学習記録として書きました。

Qiitaを読んでいる皆さんの多くは、
こうした基礎的な内容はすでに理解されているかもしれませんが、
自分の中でちゃんと腹落ちさせたくて、あえて記事としてまとめています。

今後はもっと実践的な設計パターンや、
クラス設計における“継承と委譲の使い分け”などにも踏み込んでいけたらと思っています。

読んでくださった方、ありがとうございました 🙏
もし「この観点もあるよ」などあれば、ぜひコメントで教えていただけると嬉しいです!

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?