Inheritance, Interfaces and Polymorphism
Learn how a class can extend another with virtual and override, how interfaces and abstract classes define roles, and how polymorphism lets one loop price different items, with call counts in real output.
In this lesson you will
- Extend a class and override a method
- Define and implement an interface
- Use polymorphism in one loop
- Choose between inheritance and interfaces
About 28 minutes
Drinks, cakes and deposits
Omar now sells drinks priced per cup, cakes priced per slice and reusable cups with a deposit. Each item has a name and a price rule that differs. He wants one loop for the receipt, without a long chain of if statements that asks what kind of item each is. Object-oriented design offers inheritance and interfaces for this.
Inheritance lets a class extend another and reuse its members: class Cake : Item. A method in the base class marked virtual may be replaced in a subclass with override, and the call runs the version that belongs to the actual object, which is called dynamic dispatch. An abstract class cannot be created directly and may declare abstract members that subclasses must supply. An interface lists members that a type promises to provide, and a class can implement many interfaces but extend only one class. Polymorphism means a variable of the general type can hold any of the specific ones.
| Tool | Use it for | Limit |
|---|---|---|
| class A : B | Sharing code and data in an is-a relationship | One base class |
| abstract | A base that cannot stand alone | Cannot be created |
| interface | A role or ability | No instance data |
| virtual / override | Behaviour that varies | Only for marked members |
| sealed | Forbid further inheritance |
var items = new List<Item> { new Drink("flat white", 320), new Cake("carrot cake", 350), new ReusableCup("cup", 300), new Drink("tea", 210) };
int[] qty = { 2, 3, 1, 4 };
int total = 0;
for (int i = 0; i < items.Count; i++)
{
int p = items[i].Quote(qty[i]);
total += p;
Console.WriteLine($"{items[i].Describe()} x{qty[i]} = {p}");
}
Console.WriteLine($"total {total}, quotes computed: {Item.Quotes}");
IDescribable d = items[1];
Console.WriteLine($"cake is an Item: {d is Item}, is a Drink: {d is Drink}");
if (d is Cake c) Console.WriteLine($"pattern match gives a Cake with {c.Slices} slices per cake");
Console.WriteLine($"as Drink on a cake gives: {(d as Drink)?.Name ?? "null"}");
interface IDescribable { string Describe(); }
abstract class Item : IDescribable
{
public static int Quotes;
public string Name { get; }
protected Item(string name) { Name = name; }
public abstract int Price(int units);
public int Quote(int units) { Quotes++; return Price(units); }
public virtual string Describe() => $"{Name} [{GetType().Name}]";
}
class Drink : Item
{
readonly int cup;
public Drink(string n, int cup) : base(n) { this.cup = cup; }
public override int Price(int units) => units * cup;
}
class Cake : Item
{
readonly int slice;
public int Slices => 8;
public Cake(string n, int slice) : base(n) { this.slice = slice; }
public override int Price(int units) => units * slice;
public override string Describe() => base.Describe() + " (per slice)";
}
class ReusableCup : Item
{
readonly int deposit;
public ReusableCup(string n, int deposit) : base(n) { this.deposit = deposit; }
public override int Price(int units) => deposit;
}
flat white [Drink] x2 = 640
carrot cake [Cake] (per slice) x3 = 1050
cup [ReusableCup] x1 = 300
tea [Drink] x4 = 840
total 2830, quotes computed: 4
cake is an Item: True, is a Drink: False
pattern match gives a Cake with 8 slices per cake
as Drink on a cake gives: null
One loop priced four different kinds of item, and each line used the right rule: two flat whites cost 640, three cake slices 1050, the reusable cup is a flat deposit of 300 whatever the quantity, and four teas cost 840. The total is 2830 and the counter shows 4 quotes, one for each item. The loop never asks which kind of item it has. The method that runs is chosen from the real class of the object while the program runs.
The Cake overrides Describe and calls base.Describe() to reuse the parent text before adding its own. The is operator tests the actual type, so the item stored in the IDescribable variable is an Item but not a Drink, and the pattern d is Cake c both tests and declares a variable of the specific type. The as operator tries a conversion and gives null when it does not apply, which is why the last line shows null. Notice also how the ReusableCup ignores its units parameter. That is a hint that the model could be improved, and a good design review would ask whether a deposit belongs in the same hierarchy as an item with a per-unit price.
Check by hand: 2 x 320 = 640, 3 x 350 = 1050, the deposit 300, and 4 x 210 = 840. The sum is 640 + 1050 + 300 + 840 = 2830, the total printed.
Use it for a true is-a relationship. If an object merely has another object, keep it in a field, which is called composition.
Declare variables and parameters with the interface or base type, such as IEnumerable or IDescribable, so that the implementation can change without touching the callers.
Every program in this lesson was built and run with the .NET 8 SDK and C# 12 while the course was written. .NET and C# release every year, so check the official Microsoft documentation for the current version and for features added after .NET 8.
Practice
Add a Combo item that holds two other items and prices them together with a discount. Add a method to IDescribable with a default implementation and check that existing classes keep working. List which relationships in the model are is-a and which are has-a.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What does override do?
- Hides a class
- Replaces a virtual or abstract member in a subclass
- Deletes a method
- Makes a method static
The version of the real object runs.
How many base classes can a class have?
- One
- Two
- Any number
- None
But it can implement many interfaces.
What is polymorphism?
- One variable type running the right version for the actual object
- Having many files
- A kind of loop
- Two variables with the same name
Dynamic dispatch.
Can you create an object of an abstract class directly?
- Yes
- Only with static
- Only in Main
- No
Create a subclass instead.
What does as return when the conversion fails?
- An exception
- Zero
- The original object
- null
is gives false.
Summary
- Inheritance shares code in an is-a relationship; a class has one base class.
- virtual and override allow behaviour to vary.
- Interfaces describe abilities and a class can implement many.
- is and as test types at run time.
Questions
What is the difference between an abstract class and an interface?
An abstract class can hold fields and shared code. An interface describes abilities, and a class can implement several.
What is base?
A keyword that refers to the base class, for calling its constructor or its methods.
Is deep inheritance a good idea?
Usually not. Prefer shallow hierarchies and composition.
