Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Javaプログラマーが学ぶRuby基礎/Rubyのクラス継承

概要

Rubyのクラス継承について
Javaと変わらない部分は省略

基底クラスのメソッド呼び出し

メソッド内で以下の記述を行うことで自分と同名の基底クラスのメソッド
呼び出すことが出来ます。

super

サンプルコード

parent_class
# encoding: Shift_JIS

=begin rdoc
= ParentClassクラス
=end
class ParentClass
  def method1(str)
    puts "#{str}"
  end
end

child_class

# encoding: Shift_JIS
require_relative './parent_class'

=begin rdoc
= ChildClassクラス
=end
class ChildClass < ParentClass
  def method1(str)
    super
    puts "#{str}"
  end
end

main

# encoding: Shift_JIS
require_relative './child_class'

child = ChildClass.new
child.method1 "Hello"

出力

親Hello
子Hello