1.2 Inheriting Class

Your first inheritance

Now that we've understood inheritance works, lets do some of our own.

Pay special attention to the syntax - the < operator informs Ruby that when creating the class MyArray, it should set Array as its superclass.

Example Code:

Output Window

Here, we've created our very own MyArray which subclasses Ruby's Array. It inherits all of Array's behaviour and so has all of the same methods - and an instance of MyArray works exactly like an instance of Array.

This is however a poor example - MyArray however offers us no additional behaviour over Array and so gives us no real value.

Let's shift gears and revisit an example from the introduction to classes in the "Ruby Primer" to make this lesson more practical.

Example Code:

Output Window

If you run the example above, you'll notice that the first test talks about a square. A square, by definition, is simply a rectangle where all sides are of equal length.

The current mechanism of creating a square - creating a rectangle and passing in the same value twice - is annoying. Lets just build our own Square class that takes just one parameter to the constructor (initialize) instead of two, but inherits perimeter from Rectangle.

This way, you get a nicer syntax for squares (Square.new(3), say) and you get perimeter for free from Rectangle.


You'll need to implement your own version of initialize on Square that accepts one parameter and sets both @length and @breadth to that value. This way, you don't need to touch perimeter.

Don't forget to have Square inherit from Rectangle using the < operator.

Output Window

Congratulations, guest!

% of the book completed


This lesson is Copyright © 2011-2014 by Jasim A Basheer