Inheritance
In C#, the specialization relationship is typically implemented using inheritance. This is not the only way to implement specialization, but it is the most common and most natural way to implement this relationship.
Saying that ListBox
inherits from (or derives
from) Window
indicates that it specializes
Window
. Window
is referred to
as the base
class, and ListBox
is referred to as the
derived
class. That is,
ListBox
derives its characteristics and behaviors
from Window
and then specializes to its own
particular needs.
Implementing Inheritance
In C#, you create a derived class by adding a colon after the name of the derived class, followed by the name of the base class:
public class ListBox : Window
This code declares a new class, ListBox
, that
derives from Window
. You can read the colon as
“derives from.”
The derived class inherits all the members of the base class, both
member variables and methods. The derived class is free to implement
its own version of a base class method. It does so by marking the new
method with the keyword new
. (The
new
keyword is also discussed in Section 5.3.3,
later in this chapter.) This indicates that the derived class has
intentionally hidden and replaced the base class method, as used in
Example 5-1.
Example 5-1. Using a derived class
using System; public class Window { // constructor takes two integers to // fix location on the console public Window(int top, int left) { this.top = top; this.left = left; } // simulates drawing the window ...
Get Programming C#, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.