Roshan Book

My Tech Notebook

Learning Ruby Part 3 – Inheritance


Inheritance is simply copying all the attributes from a base class to new class. It will save you lots of typing.

E.g

class Animal

attr_accessor :name, :age , :trait

end

This is how we declare a base class

class Dog < Animal

end

And this is how Dog class copies attributes from base class Animal. Now Dog has same attributes as Animal.

Adding Additional Attributes

Suppose you want to add extra attribute called type, declare Dog class like below

class Dog < Animal

attr_accessor :type

end

And now we have added attribute to Dog class, which is not in Base class “Animal”

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: