Sergiu Posted November 16, 2012 Share Posted November 16, 2012 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 More sharing options...
Antonio Conte Posted November 16, 2012 Share Posted November 16, 2012 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. 1 Link to comment Share on other sites More sharing options...
Sergiu Posted November 18, 2012 Author Share Posted November 18, 2012 Thanks for the example, very useful.. I guess that one can say that overriding is a mean to achieve polymorphism Link to comment Share on other sites More sharing options...
Recommended Posts