Another Example3:09 with Jeremy McLain
Let's see another example of overriding a virtual method.
Polymorphism and 0:00 virtual overridable methods can be difficult to understand at first. 0:01 So let's work through another example. 0:06 This time, 0:09 we'll make a couple classes using the animal example we discussed earlier. 0:09 We'll do this in the C# repel. 0:14 To start the repel, just type csharp in the console. 0:16 Let's have a Bird class that contains a Move method. 0:19 This method will simply print Birds fly. 0:22 We'll make it virtual so that we can overwrite it in subclasses. 0:26 We'll make a subclass of the bird class named Penguin. 0:45 In the Penguins Move method, we'll print, Penguins waddle. 0:53 We need to remember to type override here cuz this is the subclass. 0:57 Now let's instantiate a Bird and call its Move method. 1:15 As expected, it says Birds fly. 1:23 Let's instantiate a Penguin and call its Move method. 1:26 Again, as expected, it prints Penguins waddle. 1:37 Now let's instantiate a penguin but assign it to a bird variable. 1:41 Remember we can do this because penguins are birds. 1:49 Even though the variable is of type bird, 1:54 the object it stores is really of type penguin. 1:56 Now let's see what happens when we call Move on this variable. 2:00 It prints Penguins waddle. 2:05 Even though we're calling Move on a bird variable, 2:08 the Move method in the bird class isn't being executed. 2:11 Instead, it's the Move method in the penguin class that was executed. 2:15 The Move method in the bird class was overridden by the Move method in 2:19 the penguin class. 2:23 This is a very powerful feature of C# because 2:25 we can write code that only deals with bird variables. 2:28 Later, as we add new types of birds, 2:31 the code still works as expected without making any changes. 2:34 This is why we were able to add a new type of invader without changing the logic 2:38 of the game as it's written in the play and fire on invader methods. 2:43 The changes are contained inside ShieldedInvader and 2:47 the rest of the game treats it like any other type of invader. 2:50 We'll get lots of practice using polymorphism to 2:54 create new types in our game. 2:56 Keep note as we go along that the core logic of the game, 2:58 as it's coded in the play method, never changes. 3:02 This is the power of polymorphism and virtual methods. 3:05
You need to sign up for Treehouse in order to download course files.Sign up