Inheritance
Prerequisites: Object-oriented programming: the big picture
class Animal {
protected string Name;
public Animal(string name) {
Name = name;
}
public virtual void MakeSound() {
Console.WriteLine($"{Name} makes a sound");
}
}
class Dog : Animal {
public Dog(string name) : base(name) {}
public override void MakeSound() {
Console.WriteLine($"{Name} barks");
}
}
Dog rex = new Dog("Rex");
rex.MakeSound(); // Rex barks
A base method must be marked virtual (or abstract) to allow
overriding — like C++, and unlike Java, C# does not make every
method overridable by default. : base(name) calls the parent's
constructor, equivalent to Java's super(name).
Common mistakes
- Forgetting
virtualon the base method — without it,overrideon the subclass is a compile error, catching the mistake immediately rather than silently doing the wrong thing.
Practice
Create a Cat class extending Animal that overrides
MakeSound() to print "<Name> meows".
Show solution
class Cat : Animal {
public Cat(string name) : base(name) {}
public override void MakeSound() {
Console.WriteLine($"{Name} meows");
}
}