| for RuBoard |
C# supports a single inheritance model. Thus a class may derive from a single base class, and not from more than one. (In fact, as we saw in the previous chapter, every class in C# ultimately derives from the root class
System.Object
. In C# we may use the alias
object
for this root class.) This single inheritance model is simple and avoids the complexities and
In this section we discuss inheritance in connection with a further elaboration of our hotel reservation case study. In the following section we will cover additional features of inheritance in C#,
With inheritance, you factor the abstractions in your object model, and put the more reusable abstractions in a high-level base class. You can add or change features in more specialized derived classes, which "inherit" the standard behavior from the base class. Inheritance facilitates code reuse and extensibility. A derived class can also provide a more appropriate interface to existing
Consider
Reservable
as a base class, with derived classes such as
Hotel
. All reservables share some characteristics, such as an id, a capacity, and a cost. Different kinds of reservables
You implement inheritance in C# by specifying the derived class in the
class
statement with a
// HotelBroker.cs
namespace OI.NetCs.Acme
[1]
{
using System;
public class Hotel : Reservable
{
public string City;
public string HotelName;
public Hotel(string city, string name,
int number, decimal cost)
: base(number, cost)
{
City = city;
HotelName = name;
}
public int HotelId
{
get
{
return unitid;
}
}
public int NumberRooms
{
get
{
return capacity;
}
}
public decimal Rate
{
get
{
return cost;
}
}
}
[1] We discuss creating a namespace with the namespace directive later in the chapter.
The class Hotel automatically has all the members of Reservable , and in addition has the fields City and HotelName .
The base class
Reservable
has members
unitid
,
capacity
, and
cost
, which are designed for internal use and are not intended to be exposed as such to the outside world. In the
Hotel
class we provide public properties
HotelId
,
NumberRooms
, and
Rate
to give
If your derived class has a constructor with parameters, you may wish to pass some of these parameters along to a base class constructor. In C# you can conveniently invoke a base class constructor by using a colon, followed by the base keyword and a parameter list.
public Hotel(string city, string name,
int number, decimal cost)
: base(number, cost)
{
City = city;
HotelName = name;
}
Note that the syntax allows you to explicitly invoke a constructor only of an immediate base class. There is no notation that allows you to directly invoke a constructor higher up the inheritance hierarchy.
| for RuBoard |