Objects and Inheritance Hierarchy

In this chapter, you will learn that everything in an inheritance hierarchy is an object.

User Defined Class

Let's define a user defined class.

class Car
end

Car

Object is the Parent of Car

This user defined Car class is part of an inheritance hierarchy. Thus, we can ask Ruby for it's super-class.

class Car
end

p Car.superclass

This prints:

Object

Object is Super Class of Car

Implicit Parent

The Car class implicitly extends from Ruby's built-in Object class. It's as if you had written code like this:

class Car < Object
end

Car is an Object

We found out that the Car class is part of an inheritance hierarchy. If everything in an inheritance hierarchy is an object, then the Car class must be an object. If Car class is an object, it must be an instance of some class. What is that class? We can ask Ruby:

class Car
end

p Car.class

This prints:

Class

The Car class is an instance of Ruby's built-in class called Class.

Car is Instance of Class

BasicObject is the Parent of Object

We know that super-class of Car is Object. The Object also has a super-class.

p Object.superclass

This prints:

BasicObject

Basic Object is Super Class of Object

Object is an Instance of Class

The Ruby's built-in Object is also part of an inheritance hierarchy. It must also be an object.

p Object.class

This prints:

Class

The Object is an instance of Ruby's built-in class called Class.

Object is Instance of Class

BasicObject Has No Parent

The Ruby's built-in BasicObject is the root of the inheritance hierarchy.

p BasicObject.superclass

This prints:

nil

The nil indicates that BasicObject has no parent.

Adam and Eve

BasicObject is an Instance of Class

BasicObject is also an object, since it has sub-classes and is part of the inheritance hierarchy. What is the class used to create an instance of BasicObject? We can ask Ruby:

p BasicObject.class

This prints:

Class

The BasicObject is an instance of Ruby's built-in class called Class.

BasicObject is Instance of Class

Visual Summary

Inheritance Hierarchy and Class

Fabio Asks

Why does user defined classes use Class as the template to create an instance?

You define classes in Ruby using the class keyword. This is the reason that the class you define becomes an instance of the Ruby's built-in class called Class.

Rhonda Asks

Why does Ruby's built-in classes use Class as the template to create an instance?

The reason is the same as the reason for user defined classes. The class keyword defines the Ruby's built-in objects like Object and BasicObject.

Key Takeaways

  • User defined classes and Ruby's built-in classes are objects.
  • User defined classes and Ruby's built-in classes are instances of class called Class.

Summary

In this chapter, you learned that everything in the inheritance hierarchy is an object.

results matching ""

    No results matching ""