O'Reilly logo

Learning C# by Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Inheritance

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 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). These members can be treated just as if they were created in the derived class.

The derived class is free to implement its own version of a base class method. This is called hiding the base class method and is accomplished by marking the method with the keyword new.

Tip

This is a different use of the keyword new than you’ve seen earlier in this book. In Chapter 8, new was used to create an object on the heap; here new is used to replace the base class method. Programmers say the keyword new is overloaded, which means that the word has more than one meaning ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required