What is Polymorphism and How Does it Work in Object-Oriented Programming?

  • Thread starter Thread starter Punkyc7
  • Start date Start date
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
1 reply · 1K views
Punkyc7
Messages
415
Reaction score
0
I am confused to what a polymorphism is. I thought that it was when a class implements an abstract class but after reading things on the web I am not sure if that is right. It seems like everyplace defines it slightly differently. So my question is am I thinking about it right or is there another definition that is the agreed upon definition?
 
Physics news on Phys.org
In its basis, polymorphism means that you can access classes that implement the same interface through that interface, without knowing which class it is. Or, put simply, where the outside of the classes looks the same - and you can use that without having to know exactly which class it is.

For example, consider often-used example of a zoo. "Before" OO, we would write things like
Code:
Animal frisk = new Cat();

// ...

if (frisk is Cat)
{
  frisk.Meow();
}
else if (frisk is Dog)
{
  frisk.Bark();
}
... // and so on

Polymorphism allows us to write
Code:
Animal frisk = new Cat();

// ...

frisk.MakeSound();

where MakeSound() is in the public interface (for example, it is defined in the abstract class Animal) and each animal knows which sound it makes, so the correct method will get called automatically.

Note that polymorphism is not the same as inheritance - although they are closely related. For example, I wouldn't say that my Ford Fiesta and your Mercedes E90 have a common base class necessarily, yet we would both know how to drive each others car because the "public interface" (position of the accelerator and brakes, etc.) are the same.
 
Last edited: