Subtyping vs Inheritance
Understand how subtyping works through inheritance in Ruby and how it enables code reuse and polymorphism. Learn the role of abstract classes and interfaces in dynamically-typed Ruby, including best practices to maintain clear and manageable code when using inheritance and modules.
We'll cover the following...
Compared to modules
Compared to modules, there is a better way to specify a new implementation while maintaining the same behaviors, meaning to reuse code and extend original software. We won’t be using an inheritance mechanism to copy over variables and methods from one object to another, but we’ll instead use subtyping.
For example, a duck, a cuckoo, and an ostrich are all subtypes of a bird:
If we know the definition of the word “inherit” from the Oxford Dictionary in regards to genetics , the diagram above makes perfect sense:
Based on our life experience, we can say that the subtypes are correct, and the abstraction above makes sense. And this fact enables polymorphism: it doesn’t matter what kind of bird it is. We can feed the bird, let it flap its wings, and so on.
From a ...