Inheritance
A C#
class can inherit from another class to extend
or customize that class. A class can only inherit from a single class
but can be inherited by many classes, thus forming a class hierarchy.
At the root of any class hierarchy is the
object
class,
which all objects implicitly inherit from. Inheriting from a class
requires specifying the class to inherit from in the class
declaration, using the C++ colon notation:
class Location { // Implicitly inherits from object string name; // The constructor that initializes Location public Location(string name) { this.name = name; } public string Name {get {return name;}} public void Display( ) { Console.WriteLine(Name); } } class URL : Location { // Inherit from Location public void Navigate( ) { Console.WriteLine("Navigating to "+Name); } // The constructor for URL, which calls Location's constructor public URL(string name) : base(name) {} }
URL
has all the members of
Location
, and a new member,
Navigate
:
class Test { static void Main( ) { URL u = new URL("http://microsoft.com"); u.Display( ); u.Navigate( ); } }
Tip
The specialized class and general class are referred to as either the derived class and base class or the subclass and superclass .
Class Conversions
A class D may be implicitly upcast to the class B it derives from, and a class B may be explicitly downcast to a class D that derives from it. For instance:
URL u = new URL( ); Location l = u; // upcast u = (URL)l; // downcast
If the downcast fails, an
InvalidCastException ...
Get C# Essentials 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.