Intro to Object Orientated Programming (3 Part Series)
This blog post will cover the object-orientated principle of polymorphism. Some of the concepts in polymorphism will also relate to inheritance.
What is Polymorphism?
Polymorphism means many forms. In OOP, this allows us to create a Superclass with a method that is inherited by its subclasses but the method in the subclass will perform a different action.
class Mammal def live_birth puts "We give birth to live animals" end end class Platypus < Mammal def live_birth puts "We lay eggs." end end duckBill = Platypus.new duckBill.live_birth #output "We lay eggs"
The above method of using polymorphism uses inheritance. The superclass and the subclass both contain the method live_birth but the Platypus class has changed the output of the method. This allows flexibility in your code.
In our Mammal class, it made sense to inherit that method because most mammals do give birth to live young, however, for the platypus class polymorphism has allowed us to override that method.
Polymorphism allows a subclass to use a method that is inherited from the superclass and to change it to meet the needs of the subclass.
The next blog post will still be about polymorphism but also include super and Modules.