Inheritance
Explore the concept of inheritance in Ruby's object-oriented programming. Understand how inheritance enables code reuse and the risks of misusing it. This lesson helps you identify correct design patterns and avoid common beginner mistakes when structuring classes.
We'll cover the following...
What inheritance is?
Inheritance is the third foundational concept in object-oriented programming. We’ve already talked about encapsulation and polymorphism.
The concept of inheritance is also somewhat controversial at the same time. There are many opinions about inheritance. Even so, we’ll take a quick look into how inheritance works in Ruby, and after that, we’ll discuss why the overuse of inheritance is bad practice.
Robot example
Imagine adding another player to the robots field along with robots and dogs — humans, so we have three types of objects: dog(s), robots, human(s). What would a junior object-oriented programmer do? They would use the following trick.
It isn’t hard to find out that we’ve got up,down, left, and right methods. We also have x and y methods, instance variables accessible through helper methods created by attr_accessor. There is also a label that is different for every object type. Methods up, down, left, and right implement some functionality that is almost always identical.
In other words, there is something that is the same and unique at the same time. Our up, down, left, and right are pretty straightforward. It’s just one line, and we will copy them over from one object to another: ...