In this post we will learn about multiple inheritance in ruby.
What is Multiple Inheritance?
It is property of code to inherit from multiple parent classes. Ruby supports inheriting only from one parent class.
So what is the way for inheriting from multiple classes? By the way are you aware of classic diamond problem in mulitple inheritance? If not, read more about it here.
Here comes in play modules in Ruby. Modules are somewhat different than classes -
- Modules can’t be instantiated, class can be instantiated
- Can’t create object of Modules, but can create object of class
- We can include multiple modules in a single class, but can’t include classes
To achieve multiple inheritance, we can include as many modules in a class. The same methods will be overriden by latest implementation. Let’s take a example -
Here module A is included in
class C and so when method
name is called upon
class C it results printing
Now let’s consider this example -
Here we have two modules
B. And when these two are included in
class C, because both define same method
name and module
B is included after A - the program output is
And that’s how we can include multiple modules in same class.
I hope this was useful!