1.1 Understanding Inheritance

Inherited behaviour

When classifying objects, it's fairly common to start out with general classes and then delve in to create sub-classes that are more specialized. Think about it:

  • Integers and Floats are both Numbers.
  • A square is also a rectangle, and both in turn are quadrilaterals.
  • Both cars and motorcycles are vehicles (but a motorcycle isn't a car).
  • This kind of parent-child relationship between classes is often referred to as inheritance, where the specialized class inherits the abilities of its more generic parent.

    Example Code:

    Output Window

    So according to Object#is_a?, the object 1.0 is both a Float and a Numeric (the class that represents a number in Ruby).

    This is a perfect example of sub-classes - here Float is a sub-class of Numeric, so 1.0 which is a Float is also a Numeric.

    Does this mean that in Ruby, 1.0 is an instance of both the Float class and the Numeric class? Let's see for ourselves.

    Example Code:

    Output Window

    Alright, obviously 1.0 is an instance of Float. So how does Numeric come into the picture?

    Example Code:

    Output Window

    Or to put it another way:

    Example Code:

    Output Window

Meet the superclass

The Class#superclass method tells you which class any given class was inherited from. Note that it's an instance method on Class and not on Object.

Let's use it walk the inheritance tree of Ruby's Float class.

Example Code:

Output Window

As you can see, in Ruby a Float is a Numeric is an Object is a BasicObject.

Each class in that chain inherits the behaviour of the class that comes next. All such chains in Ruby end with BasicObject which is a completely blank, empty class with no superclass. Calling BasicObject's superclass method returns nil.

Let us see how many methods are uniquely 1.0s and how many are inherited by it from its ancestors.

Example Code:

Output Window

Great! Now lets remove those methods that are inherited from Object. We'll skip BasicObject because it (as a conscious design decision in Ruby) has no methods at all.

Example Code:

Output Window

So there, the number dropped. Now to remove methods inherited from Numeric.

Example Code:

Output Window

Pow! We're down to just 13 methods. As you can see, it's important to understand the inheritance hierarchy of a class to know exactly what methods it has and where they come from.

Your turn to practice. As always, your objective is to make the tests pass.

Hint

Use a while loop to walk up the hierarchy starting with subclass. Stop when you get a nil (you've hit BasicObject) or when you find klass.

Output Window

Congratulations, guest!


% of the book completed

or

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