Ruby does not support Multiple Inheritance, but Ruby supports Multilevel inheritance. Some languages like C++, Perl and Python support Multiple inheritance and some like Java, C# don’t. Ruby uses Mixins
to get this problem solved. Didn’t get a clear picture…? Let’s get it then 🙂
Inheritance
is one of the most important OOPS concept. When a class B inherits from class A, class A becomes superclass and class B is child class of class A. All the properties of class A is applicable to class B.
What is Multilevel inheritance…?
When there is more than one level of inheritance, it’s MultiLevel Inheritance. Say, when class B inherits from class A, and class C inherits from class B, class C gets all properties from class B, class B gets all properties from class A. Simply stating,
class B inherits class A
class C inherits class B
it is Multilevel inheritance. This is supported by Ruby.
class Animal def my_method puts "Hi, I am a #{self.class}" end end Class Bird < Animal def method_2 puts "#{self.name} can fly high" end end Class Eagle < Bird def method_3 puts "Hi, I can fly above clouds!" end end
Animal.new.my_method # => "Hi, I am a Animal"
Bird.new.my_method # => "Hi, I am a Bird"
Bird.new.method_2 # => "Bird can fly high"
Eagle.new.method_2 # => "Eagle can fly high"
Eagle.new.method_3 # => "Hi, I can fly above clouds!"
What is Multiple inheritance...?
When a class is inherited from multiple class at the same time, we call it Multiple inheritance. Say, class C is inherited by class A as well as class B.
class C inherits class A
class C inherits class B
The above is not possible in ruby, but ruby makes use of Mixin
to solve the above. We include
a module inside a class, which gives same functionality as of Multiple inheritance.
module Animal def my_method puts "Hi, I am a #{self.class}" end end module Mammal def method_2 puts "#{self.name} is a Mammal" end end class Dog include Animal include Mammal def method_3 puts "hey, I am faithful" end end
Dog.new.method_3 # => "hey, I am faithful"
Dog.new.method_2 # => "Dog is a Mammal"
Dog.new.my_method # => "Hi, I am a Animal"