Wednesday, January 4, 2012

Inheritance in Ruby

In ruby a class can inherit the features of another class. Just like a child inherits some features of parents.


(Reference : Beginning Ruby - Peter Cooper)
#!/usr/bin/ruby


class ParentClass
        def method1
                puts "Hello World"
        end


        def method2
                puts "hello people"
        end
end


class ChildClass < ParentClass
        def method3
                puts " I am completeley different from the above two"
        end


        def method2
                puts " I override my parent"
                super
        end
end


my_object=ChildClass.new
my_object.method3
my_object.method2
my_object.method1
syntax highlighting by pygments via the monkey pygment web app

utput will be something like this,

./inheritance.rb

I am completeley different from the above two

I override my parent

hello people

Hello World

When we see the code,

the ChildClass doesn't have the methods of the ParentClass.

But when the methods of ParentClass( i.e "method1") are called with the ChildClass, we get the outputs of the methods defined in the ParentClass.

So, the ChildClass inherited the methods, rather we would call the features of the ParentClass.

There is some more things we see here too.

There is a "method2" in both the Parent and Child. In such cases, ChildClass's method i.e. "method2" overrides the "method2" of the parent class.

What is that "super" doing there?

Super makes sure that after the completion of "method2" of ChildClass the "method2" of the ParentClass is executed.

When we mention Super in a method that belongs to child class, it looks up in the inheritance chain and tries to find the method with the same name(in this case method2) in the parent class and executes it.

No comments:

Post a Comment