c# · level 2 · unit 3 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
One call, and every object answers its own way.
A derived class can replace a method it inherits, but only if the base class allows it. Marking a method in the base class says derived classes may write their own version. Each derived class then writes it again with override.
Now one array of Animal can hold dogs, cats and plain animals together. When the loop calls pet.Sound(), each object runs its own version. This is : one call, many shapes of answer.
Try override on a method that is not virtual and C# refuses with CS0506. ToString works this way too: it is virtual in every object.
using System;
Animal[] pets = { new Dog(), new Cat(), new Animal() };
foreach (Animal pet in pets)
{
Console.WriteLine(pet.Sound());
}
class Animal
{
public virtual string Sound() { return "..."; }
}
class Dog : Animal
{
public override string Sound() { return "Woof!"; }
}
class Cat : Animal
{
public override string Sound() { return "Meow!"; }
} An array of a base class can hold any object built from its derived classes.
guess first
Everyone is a worker. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
Worker[] staff = { new Worker(), new Chef(), new Worker() };
foreach (Worker w in staff)
{
Console.Write(w.Job() + " ");
}
class Worker
{
public virtual string Job() { return "work"; }
}
class Chef : Worker
{
public override string Job() { return "cook"; }
}
your turn
Your turn. Start the band.
On line 11, let derived classes replace Play. On line 19, replace it in Guitar and choose its sound. Then press run.
output
press run to see what happens
fix it
The disco light will not flash. Fix it!
output
press run to see what happens
- C# says
CS0506on line 16: it cannot overrideShinebecause it is not marked as replaceable. - The base class must allow derived classes to replace the method.
- Change line 11 to
public virtual string Shine() { return "a steady glow"; }, then press run.
nailed it
one call, many answers. :D
virtuallets derived classes replace a method.overridewrites the replacement.- Each object runs its own version: polymorphism.
new words in your collection
- virtual
- polymorphism
This lesson isn’t saved. A free account remembers every lesson you finish.