![](http://imgdetail.ebookreading.net/software_development/33/9780470596906/9780470596906__stephens-c-programming__9780470596906__bg14a.png)
// Initialize the account.
private void Form1_Load(object sender, EventArgs e)
{
// Initialize the account.
MyAccount = new BankAccount();
MyAccount.Balance = 100M;
// Register to receive the Overdrawn event.
MyAccount.Overdrawn += MyAccount_Overdrawn;
// Display the current balance.
balanceTextBox.Text = MyAccount.Balance.ToString(“C”);
}
// We’re overdrawn.
private void MyAccount_Overdrawn(object sender,
BankAccount.OverdrawnEventArgs args)
{
MessageBox.Show(“Insufcient funds.”);
}
INHERITANCE
Often when you build one class, you end up building a bunch of other closely related classes. For
example, suppose you’re building a program that models your company’s organization. You might
build an
Employee class to represent employees. After a while, you may realize that there are differ-
ent kinds of employees: managers, supervisors, project leaders, and so forth.
You could build each of those classes individually but you’d find that these classes have a lot in
common. They all probably have
FirstName, LastName, Address, EmployeeId, and other proper-
ties. Depending on the kinds of operations you need the objects to perform, you might also find
that they share a lot of methods:
ScheduleVacation, PrintTimesheet, RecordHours, and so
forth. Though you could build each of these classes individually, you would end up duplicating a
lot of code in each class to handle these common features.
Fortunately, C# allows you to make one class inherit from another and that lets them share common
code. When you make one class inherit from another one, you derive the new class from the existing
class. In that case, the new class is called the child class and the class from which it inherits is called
the parent class.
In this example, you could build a
Person class with properties that all people have: FirstName,
LastName, Street, City, State, and Zip. You could then derive the Employee class from Person
and add the new property
EmployeeId.
Next you could derive the
Manager class from Employee (because all Managers are also Employees)
and add new manager-related properties such as
DepartmentName and DirectReports.
Syntactically, to make a class that inherits from another you add a colon and the parent class’s name
after the child class. For example, the following code defines the
Manager class, which inherits
596906c23.indd 283 4/7/10 12:33:47 PM