Microsoft 9GD00001 manual Class Inheritance, Listing 3-3 Class inheritance

Models: 9GD00001

1 449
Download 449 pages 12.58 Kb
Page 93
Image 93

70Microsoft Visual Studio 2010: A Beginner’s Guide

Now that you can define a new class, create an instance from that class, and use it, the next section shows you another feature of classes called inheritance.

Class Inheritance

One class can reuse the members of another through a feature known as inheritance. In programming terms, we say a child class can derive from a parent class and that child class will inherit members (such as fields and methods) of the parent class that the parent class allows to be inherited. The following example will create a Cashier class that derives from the Employee class. To create this class, right-click the project, select Add Class, and name the class Cashier. Listing 3-3 shows the new class and modifications for implementing inheritance.

Listing 3-3 Class inheritance

C#:

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

namespace FirstProgram

{

public class Cashier : Employee

{

}

}

VB:

Public Class Cashier

Inherits Employee

End Class

The C# inheritance relationship is indicated by the colon after the Cashier identifier, followed by the class being derived from, Employee. In VB, you write the keyword Inherits, on a new line, followed by the class being derived from. Essentially, this means that Cashier has all of the same members as Employee. Listing 3-4 demonstrates the benefits of inheritance.

Page 93
Image 93
Microsoft 9GD00001 manual Class Inheritance, Listing 3-3 Class inheritance