C# / CHAPTER 12
Interfaces and virtual behavior
AdvancedSeparate a required capability from its implementation.
By the end of this chapter
- Implement an interface
- Use virtual and override correctly
- Design clients around a contract
The idea
An interface gives a shared contract to otherwise different classes. A client can receive an interface value and use its members without knowing the concrete class. An implementation must honor the meaning of the contract as well as its signatures. For example, a duration method should use consistent units across all implementations, not seconds in one class and minutes in another.
Class inheritance offers another form of polymorphism. A base instance method must be virtual, abstract, or already overridden to support an override in a derived class. Runtime dispatch then chooses the appropriate implementation for the actual object. Merely declaring a same-named method can hide a member instead, so override makes the intended behavior explicit.
using System;
IPrice price = new FixedPrice();
Console.WriteLine(price.Cents());
interface IPrice { int Cents(); }
class FixedPrice : IPrice {
public int Cents() => 325;
}325
The variable exposes the IPrice contract, while its object supplies FixedPrice.Cents. The returned amount follows the interface’s cents-based meaning.
Try it yourself
Define two shipping-fee implementations behind one interface and total their results uniformly.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING