Jump to content
Larry Ullman's Book Forums

Recommended Posts

Hi,

i have a question regarding the relationship between polymorphism and overriding. I found this definition on page 151:

"you can override a parent's class's method to customize it for the new class. This is polymorphism, where calling the same method can have different results, depending on the object type."

Are those two terms synonyms?

Thanks,

Link to comment
Share on other sites

No, but the overriding (often called method overloading) is a result of polymorphism. Does that make sense?

 

Polymorphism means "in many forms" or "with many heads". The point is that several objects that share a parent is able to behave different than they brothers. I really like some examples releated to games.

 

class Soldier {
public function attack( ) { return 5; }
}

class Archer extends Soldier {
public function attack( ) { return 10; }
}

class BadAssSoldier extends Soldier {
public function attack( ) { return 20; }
}

// A normal soldier
$soldier = new Soldier();
$soldier->attack(); // Does 5 damage

// An archer
$archer = new Archer();
$archer->attack(); // Does 10 damage

// A tough soldier
$badAssSoldier = new BadAssSoldier();
$badAssSoldier->attack(); // Does 20 damage!

 

You can really see the use of polymorphism when you don't know that kind of soldier you have.

 


// Holds an army
$army = array();

// Add some soldiers to the army
$army[0] = new Soldier();
$army[1] = new Soldier();
$army[2] = new Soldier();

// Add "tough soldiers" to the army

$army[3] = new BadAssSoldier();
$army[4] = new BadAssSoldier();

// Add archers to the army
$army[5] = new Archer();
$army[6] = new Archer();
$army[7] = new Archer();

// Now, let the army attack!
foreach ( $army as $single_soldier )
{
echo 'Attacked with a strength of: '. $single_soldier->attack(). '<br />';
}

 

The examples should be runnable if you just save them to a file and run them with a browser.

  • Upvote 1
Link to comment
Share on other sites

 Share

×
×
  • Create New...