Game Development Reference
In-Depth Information
26 //Function when player enters Tavern
27 public void EnterTavern()
28 {
29 //Everybody say greeting
30 foreach(MyCharacter C in Characters)
31 {
32 //call SayGreeting in derived class
33 //Derived class is accessible via base class
34 C.SayGreeting();
35 }
36 }
37 //-------------------------------------------------------
38 }
The following are the comments for code sample 1-14:
Line 07 : To keep track of all NPCs in the tavern, regardless of the NPC
type, a single array ( Characters ) of type MyCharacter is declared.
Lines 16-20 : The Characters array is populated with multiple NPCs of
different types. This works because, though they are of different types,
each NPC derives from the same base class.
Line 27 : The EnterTavern function is called at level startup.
Line 34 : A foreach loop cycles through all NPCs in the Characters array,
calling the SayGreeting function. The result is shown in the following
screenshot. The unique messages for each NPC are printed instead of
the generic message defined in the base class. Polymorphism allows the
overridden method in the derived classes to be called instead.
Polymorphism produces a backwards transparency between data types that share a common lineage
 
Search WWH ::




Custom Search