Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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 <code>Fraction</code> and a class called <code>ComplexNumber</code>, both of these might include a method called <code>display()</code>, but each of them would implement that method differently. In PHP, for example, you might implement it like this:</p> <pre><code>// 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-&gt;numerator = $n; $this-&gt;denominator = $d; } public function display() { echo $this-&gt;numerator . '/' . $this-&gt;denominator; } } class ComplexNumber { public $real; public $imaginary; public function __construct($a, $b) { $this-&gt;real = $a; $this-&gt;imaginary = $b; } public function display() { echo $this-&gt;real . '+' . $this-&gt;imaginary . 'i'; } } // Main program $fraction = new Fraction(1, 2); $complex = new ComplexNumber(1, 2); echo 'This is a fraction: ' $fraction-&gt;display(); echo "\n"; echo 'This is a complex number: ' $complex-&gt;display(); echo "\n"; </code></pre> <p>Outputs:</p> <pre><code>This is a fraction: 1/2 This is a complex number: 1 + 2i </code></pre> <p>Some of the other answers seem to imply that polymorphism is used only in conjunction with inheritance; for example, maybe <code>Fraction</code> and <code>ComplexNumber</code> both implement an abstract class called <code>Number</code> that has a method <code>display()</code>, which Fraction and ComplexNumber are then both obligated to implement. But you don't <em>need</em> inheritance to take advantage of polymorphism.</p> <p>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 <code>Number</code> created:</p> <pre><code>$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-&gt;display(); echo "\n"; </code></pre> <p>In this case, the appropriate <code>display()</code> 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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload