Object Oriented Programming

Inheritance in Ruby

Inheritance is used to inherit another class' members, including fields and methods. A sub class extends a super class' members.


Syntax
class subClass < superClass
    #to access a super class method
    super(methodName)
end

Notes

Instance variables are not inherited.

If a method is written in the subclass with the same name and parameters as one in the parent class, the super class' method is overwritten.

With class extension, when referring specifically to a super class member, use the keyword 'super'.


Example
class Cat
    def initialize
        @name = "Garfield"
    end

    def sound #implemented sound method from interface
        return "Meow"
    end
end

class Tiger < Cat
    def initialize #will overwrite Cat constructor
        @name = "Mike Tyson Jr."
    end

    def sound #will overwrite the Cat sound method
        return "Roar"
    end

    def catSound
        super(sound) #will call cat's sound
    end
end

See Also
Documentation

Class - Ruby API

Add to Slack

< Instantiation   |   Modules >

© 2019 SyntaxDB. All Rights Reserved.