DEV Community

Cover image for What is Object Orientated Programming (Part-three) Polymorphism?
Aweys Ahmed
Aweys Ahmed

Posted on

1

What is Object Orientated Programming (Part-three) Polymorphism?

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"

Enter fullscreen mode Exit fullscreen mode

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.

Summary

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.

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay