Inheritance and interfaces
Inheritance and interfaces
Inheritance
A derived class reuses and extends another class (: means "inherits").
class Animal
{
public string Name { get; set; }
public virtual string Speak() => "...";
}
class Dog : Animal
{
public override string Speak() => "Woof!";
}
class Cat : Animal
{
public override string Speak() => "Meow!";
}
virtual lets derived classes change the behaviour, override does the change.
Polymorphism
List<Animal> pets = new() { new Dog { Name = "Rex" }, new Cat { Name = "Tom" } };
foreach (var p in pets)
Console.WriteLine($"{p.Name}: {p.Speak()}"); // Rex: Woof! / Tom: Meow!
The variable's type is Animal, but the method of the real object runs.
Interfaces
An interface describes a contract — what an object can do, not how.
interface IPayable
{
decimal GetAmount();
}
class Invoice : IPayable
{
public decimal Total { get; set; }
public decimal GetAmount() => Total;
}
A class can inherit only one class, but implement many interfaces.
Which one?
| Situation | Choice |
|---|---|
| "is a kind of" + shared code | inheritance |
| "can do" — a contract | interface |
The most common mistakes
- Forgetting
override— the method hides instead of replacing the base one. - Deep hierarchies — composing objects is often clearer.
Practice
Add a Bird class whose Speak() returns "Tweet!" and put it in the same list.