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 : 基本的な継承クラスの使い方

Posted at
sample.rb

class Greeting
	def hello
		puts "こんにちは #{@name}さん"
	end

	def goodmorning
		puts "おはよう #{@name}さん"
	end

	def goodevening
		puts "こんばんわ #{@name}さん"
	end
end

class Tanaka < Greeting
	# Greeting を継承
	def initialize(name)
		@name = name
	end

	def goodbye
		# Tanaka クラスのオブジェクトで使用可能な goobye メソッド
		puts "#{@name}さん さよなら"
	end
end

class Sato < Greeting
	# Greeting を継承
	def initialize(name)
		@name = name
	end
end


tanaka = Tanaka.new("Tanaka")
tanaka.hello #=>こんにちは Tanakaさん
tanaka.goodmorning #=>おはよう Tanakaさん
tanaka.goodevening #=>こんばんわ Tanakaさん
tanaka.goodbye #=>Tanakaさん さよなら

sato = Sato.new("Sato")
sato.hello #=><こんにちは Satoさん
sato.goodmorning #=>おはよう Satoさん
sato.goodevening #=>こんばんわ Satoさん
#sato.goodbye => エラー

# Userオブジェクトなので継承したGreetingクラスのhelloメソッドを使用可能
#継承の使い方は複数あるクラスの共通処理をまとめて置いたりする。
# => つまり継承元にメソッドを定義しておくことによって複数のクラスオブジェクトで使うことが
#可能となる。


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?