Ruby Basics : Inheritance
In this article you will learn about inheritance and how the method look-up works in an inheritance hierarchy.
We will not discuss the why and when inheritance must be used. It is beyond the scope of this article series. Please checkout Nothing is Something presentation by Sandi Metz or Essential Object Oriented Analysis for a good discussion on this topic.
Inheritance represents is-a relationship between classes. We can say,
Car **is a** Vehicle.
We can define Car as the sub class of Vehicle.
class Vehicle def drive 'drive method' end end class Car < Vehicle end car = Car.new p car.drive
The less than symbol, <, is the syntax for inheritance. This prints:
In this example, the Car class will inherit the behavior of its parent class, Vehicle.
In the above example, when Ruby encounters the drive message sent to a car object, it looks for the drive method in the Car class. It does not find it there. It goes to the super class, Vehicle of the Car class. It finds the drive method in Vehicle. It executes that method.
What happens when you call a method that does not exist in the parent?
class Vehicle def drive p 'driving' end end class Car < Vehicle end car = Car.new car.stop
This raises a NoMethodException error. In general, Ruby looks in the class of the object receiving the message for the method. If it does not find the method, it goes to its parent and looks for the method. It keeps searching through the inheritance hierarchy until it finds the method. What happens when Ruby reaches the root of inheritance hierarchy and still does not find the method? In that case, it raises NoMethodException.
Why does Ruby look for the method in the Car class?
The instance methods live in the class. We discussed this concept in the What is an Object? article.
In Ruby, a class can have only one parent, so, there is no multiple inheritance.
Let's check the super class of the Car class.
class Vehicle def drive 'drive method' end end class Car < Vehicle end p Car.superclass
We see that there is one value for the super-class.
The arrow pointing to the Vehicle class is the notation for inheritance. In this example the inheritance is explicit because we can see it in the code.
Even if you don't have an explicit superclass in the code, any class you define will have one superclass. Let's look at an example.
class Car end p Car.superclass
The Car class has the Ruby built-in Object as its superclass.
In this article, you learned about inheritance and that Ruby is a single inheritance language. You learned that any user defined class has either an explicit or an implicit parent. We briefly saw how the method look-up occurs in an inheritance hierarchy.