Contents
Overview 1
Deriving Classes 2
Implementing Methods 10
Using Sealed Classes 27
Using Interfaces 29
Using Abstract Classes 42
Lab 10.1: Using Inheritance to Implement
an Interface 52
Review 70
Module 10:
Inheritance in C#
Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, places or events is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no
part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.
the base class from the derived class.
Declare methods as virtual and override or hide them as required.
Seal a class so that it cannot be derived from.
Implement interfaces by using both the implicit and the explicit methods.
Describe the use of abstract classes and their implementation of interfaces.
Materials and Preparation
This section provides the materials and preparation tasks that you need to teach
this module.
Required Materials
To teach this module, you need the following materials:
Microsoft® PowerPoint® file 2124C_10.ppt
Module 10, “Inheritance in C#”
Lab 10.1, Using Inheritance to Implement an Interface
Preparation Tasks
To prepare for this module, you should:
Read all of the materials for this module.
Read the instructor notes and delivery tips for the module.
Examine the two examples that are presented on separate slides in the topic
Using Abstract Classes in a Class Hierarchy.
Complete the lab.
Presentation:
60 Minutes
Lab:
75 Minutes
iv Module 10: Inheritance in C#
This section describes abstract classes. Define them and describe how to
declare a class as abstract. Then discuss the role played by abstract classes
in a hierarchy consisting of an interface, an abstract class, and a concrete
class, and the implications of whether they implement an interface. Then
compare abstract classes to interfaces and discuss the implementation of
abstract methods. Finally, use the review slide to reinforce the main
concepts covered in the module.
Module 10: Inheritance in C# 1 Overview
Deriving Classes
Implementing Methods
Using Sealed Classes
Using Interfaces
Using Abstract Classes
*****************************
ILLEGAL FOR NON-TRAINER USE******************************
Inheritance, in an object-oriented system, is the ability of an object to inherit
data and functionality from its parent object. Therefore, a child object can
substitute for the parent object. Also, by using inheritance, you can create new
classes from existing classes instead of starting at the beginning and creating
them new. You can then write new code to add the features required in the new
class. The parent class on which the new class is based is known as a base
class, and the child class is known as a derived class.
When you create a derived class, it is important to remember that a derived
class can substitute for the base class type. Therefore, inheritance is a type-
classification mechanism in addition to a code-reuse mechanism, and the former
Extending Base Classes
Accessing Base Class Members
Calling Base Class Constructors
*****************************
ILLEGAL FOR NON-TRAINER USE******************************
You can only derive a class from a base class if the base class was designed to
enable inheritance. This is because objects must have the proper structure or
inheritance cannot work effectively. A base class that is designed for
inheritance should make this fact clear. If a new class is derived from a base
class that is not designed appropriately, then the base class might change at
some later time, and this would make the derived class inoperable.
After completing this lesson, you will be able to:
Derive a new class from a base class.
Access the members and constructors of the base class from the derived
class.
Topic Objective
To provide an overview of
the topics covered in this
section.
Lead-in
In this lesson, you will learn
how to derive a class from a
base class.
Module 10: Inheritance in C# 3 Extending Base Classes
Syntax for deriving a class from a base class
Base class
Base class
Base class
Colon
Colon
Colon
*****************************
ILLEGAL FOR NON-TRAINER USE******************************
Deriving a class from a base class is also known as extending the base class. A
C# class can extend at most one class.
Syntax for Deriving a Class
To specify that one class is derived from another, you use the following syntax:
class Derived: Base
{
}
The elements of this syntax are labeled on the slide. When you declare a
derived class, the base class is specified after a colon. The white space around
the colon is not significant. The recommended style for using this syntax is to
include no spaces before the colon and a single space after it.
Derived Class Inheritance
A derived class inherits everything from its base class except for the base class
constructors and destructors. Public members of the base class are implicitly
public members of the derived class. Private members of the base class, though
inherited by the derived class, are accessible only to the members of the base
class.
Topic Objective
To describe the procedure
class Token
{ class Outside
protected string name; {
} void Fails(Token t)
class CommentToken: Token {
{
public string Name( ) t.name
{
return name; }
} }
}
class Token
{ class Outside
protected string name; {
} void Fails(Token t)
class CommentToken: Token {
{
public string Name( ) t.name
{
return name; }
} }
}
*****************************
ILLEGAL FOR NON-TRAINER USE******************************
The meaning of the protected access modifier depends on the relationship
class Base
{
protected string name;
}
class Derived: Base
{
}
class FurtherDerived: Derived
{
void Compiles( )
{
Console.WriteLine(name); // Okay
}
}
Protected Members and Methods
Methods of a derived class can only access their own inherited protected
members. They cannot access the protected members of the base class through
references to the base class. For example, the following code will generate an
error:
class CommentToken: Token
{
void Fails(Token t)
{
Console.WriteLine(t.name); // Compile-time error
}
}
{
public CommentToken(string name) : base(name) { }
}
class Token
{
protected Token(string name) { }
}
class CommentToken: Token
{
public CommentToken(string name) : base(name) { }
}
*****************************
ILLEGAL FOR NON-TRAINER USE******************************
To call a base class constructor from the derived class constructor, use the
keyword base. The syntax for this keyword is as follows:
C( ): base( ) { }
The colon and the accompanying base class constructor call are together known
as the constructor initializer.
Constructor Declarations
If the derived class does not explicitly call a base class constructor, the C#
compiler will implicitly use a constructor initializer of the form
:base( ).
This implies that a constructor declaration of the form
C( ) { }
{
public CommentToken(string name) { } // Error here
}
The error occurs because the CommentToken constructor implicitly contains a
:base( ) constructor initializer, but the base class Token does not contain a
parameterless constructor. You can fix this error by using the code shown on
the slide.
Constructor Access Rules
The access rules for a derived constructor to call a base class constructor are
exactly the same as those for regular methods. For example, if the base class
constructor is private, then the derived class cannot access it:
class NonDerivable
{
private NonDerivable( ) { }
}
class Impossible: NonDerivable
{
public Impossible( ) { } // Compile-time error
}
In this case, there is no way for a derived class to call the base class constructor.
Module 10: Inheritance in C# 9 Scoping an Identifier
You can use the keyword base to also qualify the scope of an identifier. This
can be useful, since a derived class is permitted to declare members that have
the same names as base class members. The following code provides an
Working with the new Keyword
Practice: Implementing Methods
Quiz: Spot the Bugs
*****************************
ILLEGAL FOR NON-TRAINER USE******************************
You can redefine the methods of a base class in a derived class when the
methods of the base class have been designed for overriding.
After completing this lesson, you will be able to:
Use the virtual method type.
Use the override method type.
Use the hide method type.
Topic Objective
To provide an overview of
the topics covered in this
section.
Lead-in
In this lesson, you will learn
about implementing
methods in derived classes.
Module 10: Inheritance in C# 11 Defining Virtual Methods
Syntax: Declare as virtual
Virtual methods are polymorphic
class Token
{
keyword is shown on the slide.
When you declare a virtual method, it must contain a method body. If it does
not contain a body, the compiler will generate an error, as shown:
class Token
{
public virtual string Name( ); // Compile-time error
}
Topic Objective
To describe how to
implement virtual methods.
Lead-in
You can use virtual methods
to allow your classes to
become polymorphic.
Note
Delivery Tip
The content in the three
topics about the virtual,
override, and new
keywords will be combined
in the practice exercise.
12 Module 10: Inheritance in C# Working with Virtual Methods
To use virtual methods:
You cannot declare virtual methods as static
You cannot declare virtual methods as private
class CommentToken: Token
{
public override string Name( ) { }
}
class Token
{
public virtual string Name( ) { }
}
class CommentToken: Token
{
public override string Name( ) { }
}
*****************************
ILLEGAL FOR NON-TRAINER USE******************************
An override method specifies another implementation of a virtual method. You
define virtual methods in a base class, and they can be polymorphically
overridden in a derived class.
Keyword Syntax
You declare an override method by using the keyword override, as shown in
the following code:
class Token
{
public virtual string Name( ) { }
}
class CommentToken: Token
{
public override string Name( ) { }
}
public int LineNumber( ) { }
public virtual string Name( ) { }
}
class CommentToken: Token
{
public override int LineNumber( ) { }
public override string Name( ) { }
}
class Token
{
public int LineNumber( ) { }
public virtual string Name( ) { }
}
class CommentToken: Token
{
public override int LineNumber( ) { }
public override string Name( ) { }
}
*****************************
ILLEGAL FOR NON-TRAINER USE******************************
To use override methods effectively, you must understand a few important
restrictions:
You can only override identical inherited virtual methods.
You must match an override method with its associated virtual method.
You can override an override method.
protected virtual string Name( ) { }
}
class CommentToken: Token
{
public override void Name(int i) { } // Errors
}
You Can Override an Override Method
An override method is implicitly virtual, so you can override it. Following is an
example:
class Token
{
public virtual string Name( ) { }
}
class CommentToken: Token
{
public override string Name( ) { }
}
class OneLineCommentToken: CommentToken
{
public override string Name( ) { } // Okay
}
Delivery Tip
The words used here are
carefully chosen: An
override method must
override an identical
inherited virtual method.
16 Module 10: Inheritance in C#
class CommentToken: Token
{
new public int LineNumber( ) { }
}
class Token
{
public int LineNumber( ) { }
}
class CommentToken: Token
{
new public int LineNumber( ) { }
}
*****************************
ILLEGAL FOR NON-TRAINER USE******************************
You can hide an identical inherited method by introducing a new method into
the class hierarchy. The old method that was inherited by the derived class from
the base class is then replaced by a completely different method.
Keyword Syntax
You use the new keyword to hide a method. The syntax for this keyword is as
follows:
class Token
{
public int LineNumber( ) { }
}
class CommentToken: Token
{
new public int LineNumber( ) { }
public int LineNumber( ) { }
public virtual string Name( ) { }
}
class CommentToken: Token
{
new public int LineNumber( ) { }
public override string Name( ) { }
}
*****************************
ILLEGAL FOR NON-TRAINER USE******************************
By using the new keyword, you can do the following:
Hide both virtual and non-virtual methods.
Resolve name clashes in code.
Hide methods that have identical signatures.
Each of these tasks is described in detail in the following subtopics.
Topic Objective
To describe how to use the
new keyword effectively for
hiding methods.
Lead-in
To use the new keyword
effectively, you need to
understand the features and
restrictions it imposes.
Module 10: Inheritance in C# 19 Hide Both Virtual and Non-Virtual Methods
class Token
{
public virtual int LineNumber( ) { }
}
class CommentToken: Token
{
public int LineNumber( ) { }
}
When you compile this code, you will receive a warning stating that
CommentToken.LineNumber hides Token.LineNumber. This warning
highlights the name clash. You then have three options to choose from:
1. Add an override qualifier to CommentToken.LineNumber.
2. Add a new qualifier to CommentToken.LineNumber. In this case, the
method still hides the identical method in the base class, but the explicit
new tells the compiler and the code maintenance personnel that the name
clash is not accidental.
3. Change the name of the method.
Delivery Tip
In many ways, the most
important point in this topic
is the tip, which emphasizes
the orthogonal meaning of
new.
This topic covers a lot of
other details, not all of which
need to be covered in class.
Tip
You can also use the new keyword to hide fields and nested classes.
Note
Module 10: Inheritance in C# 21 Practice: Implementing Methods
class A {
public virtual void M() { Console.Write("A"); }
}
class B: A {
public override void M() { Console.Write("B"); }
}
class C: B {
new public virtual void M() { Console.Write("C"); }
}
class D: C {
public override void M() { Console.Write("D"); }
static void Main() {
D d = new D(); C c = d; B b = c; A a = b;
d.M(); c.M(); b.M(); a.M();
}
}
class A {
public virtual void M() { Console.Write("A"); }
}
class B: A {
public override void M() { Console.Write("B"); }
}
one individually.
The first statement is
d.M( )
This is a call to D.M, which is declared override and hence is implicitly virtual.
This means that at run time the compiler calls the most derived implementation
of D.M in the object of type D. This implementation is D.M, which writes D to
the console.
Topic Objective
To reinforce the concepts of
virtual, override, and new.
Lead-in
Work through this code and
figure out what the output
will be.
Delivery Tip
This is an important
practice. If the students
understand this practice and
derive the correct answer,
they will have understood
virtual, override, and new.