imotanの気になる木

21歳、大学4年(未就活)の意識高い系の大学生の日記的ブロクです。

rubyの継承とオーバーライドについてまとめて見た

オーバーライドとは?

オーバーライドとは、親クラスで定義しているメソッドを子クラスで上書きすること 例

class Human
    def eat
        puts "ご飯を食べた"
    end
end
 
class Programmer < Human
    def work
        puts "コードを書いた"
    end
 
    def eat
        puts "急いでご飯を食べた"
    end
end
 
programmer = Programmer.new
programmer.eat #=> 急いでご飯を食べた

親クラスのメソッドを呼ぶ方法

親クラスのメソッドを上書きせずに、子クラスで使用する方法 superを用いる!!

class Human
    def sleep
        puts "寝た"
    end
end
 
class Programmer < Human
    def sleep
        <b>super</b>←親クラスのsleepを実行
        puts "しかし何故かぐっすり眠れない"
    end
end
 
programmer = Programmer.new
programmer.sleep
 
#実行結果
#寝た
#しかし何故かぐっすり眠れない

superに引数を渡す

class Foo
    def plus_5 num=0
        puts num + 5
    end
end
 
class Bar < Foo
    def plus_5 num
        <b>super num</b>
        <b>super</b>
    end
end
 
bar = Bar.new
bar.plus_5 3
 
#実行結果
#8
#8

superに引数を渡さなくてもおんなじ出力結果になっている!! つまり、superで親クラスのメソッドを呼ぶ際、わざわざ引数を渡さなくてもよい。