Inheritance
Now that you have the background of specialization down, and a starting-point example to work with, you can see how to use this idea in your code. In C#, the specialization relationship is implemented using a principle called inheritance. This is not the only way to implement specialization, but it is the most common and most natural way.
Saying that ListBox inherits from (or derives from) Control indicates that it specializes Control. Control 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 Control and then specializes to its own particular needs.
Tip
You’ll often see the immediate base class referred to as the parent class and the derived class referred to as the child class, whereas the topmost class, Object, is called the root class.
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 : Control
This code declares a new class, ListBox, which derives from Control. You can read the colon as “derives from.”
The derived class inherits all the members of the base class (both member variables and methods). In other words, suppose Control has member fields called top and left, to indicate where on the screen the upper-left corner of the Control will be drawn. If ListBox derives from Control, ListBox also has the member fields top and left. The same is true of methods: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access