Inheritance Basics
In this chapter you will learn about inheritance and how the method look-up works in an inheritance hierarchy.
Scope
We will not discuss the why and when inheritance must be used. It is beyond the scope of this book. Please checkout Nothing is Something presentation by Sandi Metz or Essential Object Oriented Analysis for a good discussion on this topic.
Inheritance
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:
drive method
In this example, the Car class will inherit the behavior of its parent class, Vehicle.
Method Lookup
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.
Fabio Asks
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? chapter.
Single Inheritance
Explicit Inheritance
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
This prints:
Vehicle
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.
Implicit Inheritance
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
This prints:
Object
The Car class has the Ruby built-in Object as its superclass.
Summary
In this chapter, 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.