Object-Oriented Programming: Modules
In the above code, the Pet
class houses all of the behaviors necessary for a derived-class to adopt the general behaviors of a Pet, and add on any specialized behavior specific to the type of the derived class.
However, this [Single Inheritance] presents an issue when two or more derived-classes exhibit identical behaviors that are not general to all of the derived-classes of a base-class.
In the code above, I want the Dog
and Fish
classes both to contain swim()
, but any object of Cat
must not contain swim()
. For this example, cats are not able to swim. Additionally, we do not want to have redundant code like the code on lines 13 and 25, where both classes are defining the sameswim()
method.
Unfortunately, Ruby does not offer the functionality for a derived class to inherit from multiple superclasses via the ‘classical’ inheritance operator <
. I can’t create another base-class for the Cat
and Dog
classes to inherit from, in addition to the class. This is a situation requiring multiple inheritance.
However, Ruby offers a solution to the question of multiple inheritance: modules. Modules group methods common to the sub-classes that the module is planned to be mixed into. Meaning, a module takes redundant code that exists in multiple classes and abstracts them into a single unit that can be incorporated into whichever classes the programmer deems necessary.
In the code above, compared to the first code example, swim()
has been extracted out of the Dog
and Fish
classes into the module CanSwim
. The CanSwim
module is then mixed into the Dog
and Fish
classes to implement swim()
.
Now, Dog
and Fish
inherit behavior from the Pet
class as well as having behavior mixed-in from the CanSwim
module.
Summary:
In this article, I have attempted to highlight the following topics:
- What is single inheritance?
- What are multiple ininheritancesWhat is a module?
- What is the purpose of a module?
- What situations call for the use of a module?
- How do I write code demonstrating multiple inheritance, single inheritance, and mixing-in modules?
Many thanks to the helpful staff at Launch School for assistance during my studies!