What is polymorphism, what is it for, and how is it used?
Polymorphism is the ability of the programmer to write methods of the same name that do different things for different types of objects, depending on the needs of those objects. For example, if you were developing a class called Fraction
and a class called ComplexNumber
, both of these might include a method called display()
, but each of them would implement that method differently. In PHP, for example, you might implement it like this:
// Class definitions
class Fraction
{
public $numerator;
public $denominator;
public function __construct($n, $d)
{
// In real life, you'd do some type checking, making sure $d != 0, etc.
$this->numerator = $n;
$this->denominator = $d;
}
public function display()
{
echo $this->numerator . '/' . $this->denominator;
}
}
class ComplexNumber
{
public $real;
public $imaginary;
public function __construct($a, $b)
{
$this->real = $a;
$this->imaginary = $b;
}
public function display()
{
echo $this->real . '+' . $this->imaginary . 'i';
}
}
// Main program
$fraction = new Fraction(1, 2);
$complex = new ComplexNumber(1, 2);
echo 'This is a fraction: '
$fraction->display();
echo "\n";
echo 'This is a complex number: '
$complex->display();
echo "\n";
Outputs:
This is a fraction: 1/2
This is a complex number: 1 + 2i
Some of the other answers seem to imply that polymorphism is used only in conjunction with inheritance; for example, maybe Fraction
and ComplexNumber
both implement an abstract class called Number
that has a method display()
, which Fraction and ComplexNumber are then both obligated to implement. But you don't need inheritance to take advantage of polymorphism.
At least in dynamically-typed languages like PHP (I don't know about C++ or Java), polymorphism allows the developer to call a method without necessarily knowing the type of object ahead of time, and trusting that the correct implementation of the method will be called. For example, say the user chooses the type of Number
created:
$userNumberChoice = $_GET['userNumberChoice'];
switch ($userNumberChoice) {
case 'fraction':
$userNumber = new Fraction(1, 2);
break;
case 'complex':
$userNumber = new ComplexNumber(1, 2);
break;
}
echo "The user's number is: ";
$userNumber->display();
echo "\n";
In this case, the appropriate display()
method will be called, even though the developer can't know ahead of time whether the user will choose a fraction or a complex number.