×

c# · level 2 · unit 3 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.