WeCodeAcademy

C# Inheritance and Interfaces

ExampleC#
using System;

interface ISpeaker
{
    string Speak();
}

class Animal : ISpeaker
{
    protected string name;
    public Animal(string name) { this.name = name; }
    public virtual string Speak() { return "..."; }
}

class Dog : Animal
{
    public Dog(string name) : base(name) { }
    public override string Speak() { return name + " says woof"; }
}

class Cat : Animal
{
    public Cat(string name) : base(name) { }
    public override string Speak() { return name + " says meow"; }
}

class Program
{
    static void Main()
    {
        Animal[] pets = { new Dog("Rex"), new Cat("Tom"), new Animal("Generic") };
        foreach (Animal a in pets)
        {
            Console.WriteLine(a.Speak());
        }
    }
}
Output
Rex says woof
Tom says meow
...
Quick check

Which keyword marks a method that child classes may override?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.