Inheritance

A class can inherit from another class to extend or customize the original class. Inheriting from a class allows you to reuse the functionality in that class instead of building it from scratch. A class can inherit from only a single class, but can itself be inherited by many classes, thus forming a class hierarchy. A well-designed class hierarchy is one that reasonably generalizes the nouns in a problem space. For example, there is a class called Image in the System.Drawing namespace, which the Bitmap, Icon, and Metafile classes inherit from. All classes are ultimately part of a single giant class hierarchy, of which the root is the Object class. All classes implicitly inherit from it.

In this example, we start by defining a class called Location. This class is very basic, and provides a location with a name property and a way to display itself to the console window:

class Location { // Implicitly inherits from object
  string name;
  
  // The constructor that initializes Location
  public Location(string n) {
    name = n;
  }
  public string Name {get {return name;}}
  public void Display( ) {
    System.Console.WriteLine(Name);
  }
}

Next, we define a class called URL, which will inherit from Location. The URL class has all the same members as Location, as well as a new member, Navigate. Inheriting from a class requires specifying the class to inherit from the class declaration, using the C++ colon notation:

class URL : Location { // Inherit from Location public void Navigate( ) { System.Console.WriteLine("Navigating ...

Get C# in a Nutshell, 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.