• Support PF! Buy your school textbooks, materials and every day products Here!

Polymorphism Question

  • Thread starter Punkyc7
  • Start date
  • #1
420
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?
 

Answers and Replies

  • #2
CompuChip
Science Advisor
Homework Helper
4,302
47
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:

Related Threads on Polymorphism Question

Replies
1
Views
553
Replies
2
Views
1K
Top