Confused about super keyword and inheritance


#1



https://www.codecademy.com/en/courses/ruby-beginner-en-MFiQ6/3/5?curriculum_id=5059f8619189a5000201fbcb


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
    end
end

my_message = Message.new("test","test2")

class Email < Message
    def initialize(from, to)
        super
    end
end


#2

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.


#3

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


#4

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.


#5

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?


#6

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


#7

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