Chapter 4. Extensibility and Polymorphism
In the previous chapter, we saw how to define various types of classes and specify their members—fields, properties, and functions.
In this chapter, we’re going to start by looking at this again in more detail, and try to understand what underlying concepts we’re implementing when we use these different coding patterns. We’ll then introduce a couple of new concepts—inheritance and polymorphism—and the language features that help us implement them.
We’ve finished our ATC application, by the way. Having gotten a reputation for building robust mission-critical software on time and to spec, we’ve now been retained by the fire department to produce a training and simulation system for them. Example 4-1 shows what we have so far.
Example 4-1. Classes representing firefighters and fire trucks
class Firefighter
{
public string Name { get; set; }
public void ExtinguishFire()
{
Console.WriteLine("{0} is putting out the fire!", Name);
}
public void Drive(Firetruck truckToDrive, Point coordinates)
{
if (truckToDrive.Driver != this)
{
// We can't drive the truck if we're not the driver
// But just silently failing is BADBAD
// What we need is some kind of structured means
// of telling the client about the failure
// We'll get to that in Chapter 6 return; } truckToDrive.Drive(coordinates); } } class Firetruck { public Firefighter Driver { get; set; } public void Drive(Point coordinates) { if (Driver == null) { // We can't drive if there's no driver return; ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access