Inheritance is an important concept to understand in Ruby, but it is little complex. So we will look at some examples first.
Let's think about different types of vehicles we see day to day, like Bicycle, Car and Truck.
Bicycle:
A Bicycle could have specifications such as number wheels, seats,
what type of chain, a carrier and owner's name etc.
Car:
A Car being more complex has many more specifications such as fuel type, engine details,
is it a automatic or a manual transmission, is it a hatchback or a SUV etc.
Truck:
A Truck may have some unique specifications, like how much cargo_carrying_capacity it has, is it a multiaxle vehicle or not etc.
We could observe that we are repeating ourselves again & again,
except few unqiue specifications. This is something we would always want to avoid while coding. Some specs are common across all the vehicles, like number_of_wheels, number_of_seats, owner_name and year_of_manufacture.
So let's create a class Vehicle with all the common characteristics of a vehicle.
Similarly, Car and Truck also has common features like fuel_type, chassis_number and some engine related details. So let's create another class EnginePoweredVehicle for that.
Now in Ruby we can re-write our Bicycle class again as below:
As Bicycle inherits all the common methods(features) of a Vehicle, plus 2 more like chain_manufacturer
and additional_seating_at_carrier
. So, the code written above and below are equivalent:
Similarly, Car class inherits all the (features) of a Vehicle as well as EnginePoweredVehicle. So we can re-write our Car class as below:
And, our Truck class could re-written as below:
Hold on to this and let's move on to the next page to understand further...