Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
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.
Code View:
Scroll
/
Show All 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;
}
Console.WriteLine("Driving to {0}", coordinates);
}
}
|
We have a model of the Firetruck, which uses a Firefighter as its Driver. The truck can be instructed to drive somewhere (if it has a driver), and you can tell a Firefighter to drive the truck somewhere (if he is the designated driver).
You can think of this as modeling a relationship between a Firetruck and its Driver. That driver has to be a Firefighter. In object-oriented design, we call this relationship between classes an association.