Confused about super keyword and inheritance


My code is behaving correctly but my question is why is the super keyword needed in initialize method
of the Email class if it is a subclass of the Message class

class Message
    @@messages_sent = 0
    def initialize(from,to)
        @from = from
        @to = to
        @@messages_sent += 1

my_message ="test","test2")

class Email < Message
    def initialize(from, to)


The super keyword looks for and (if found) executes the first method with the same name and signature it finds along the ancestor chain. So right now in your code, the super keyword finds the similarly named initialize method in the parent class and executes it.

I'm not sure if I that clear enough, do ask any questions you have, I'll be happy to answer them.


So if I'm not overwriting the method why do I have to use the super keyword. The method should be accessible regardless since it is inherited


In this case initialize is a special method, so in order to call the parent one you should use super. If you try and call initialize from within initialize you'll run into SystemStackError (or endless recursion). Since the ruby interpreter will look for initialize method and will call the first one it finds (the one from inside the child class). super directs the interpreter up the inheritance chain.

So in short - No, methods aren't easily accessible since they're inherited.


Hmm, so let me get this straight. Since initialize is a special method we
have to use the super keyword but as a best practice we should use the
super keyword when ever we want to access a method from a parent class?


Exactly right. Try and always use super, it's a good practice. You can also use alias_method to call parent methods but it gets weirder and uglier pretty quickly. I think the answers to this StackOverflow question sum it up quite well


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.