Skip to Main Content
C# in a Nutshell, Second Edition
book

C# in a Nutshell, Second Edition

by Peter Drayton, Ben Albahari, Ted Neward
August 2003
Intermediate to advanced content levelIntermediate to advanced
928 pages
32h 1m
English
O'Reilly Media, Inc.
Content preview from C# in a Nutshell, Second Edition

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 ...
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.
Start your free trial

You might also like

C# in a Nutshell

C# in a Nutshell

Ben Albahari, Ted Neward, Peter Drayton
C# 7.0 in a Nutshell

C# 7.0 in a Nutshell

Joseph Albahari, Ben Albahari
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
C# Cookbook

C# Cookbook

Stephen Teilhet, Jay Hilyard

Publisher Resources

ISBN: 0596005261Catalog PageErrata