
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Implementing Polymorphism with Interfaces
|
145
3.16 Implementing Polymorphism with Interfaces
Problem
You need to implement polymorphic functionality on a set of existing classes. These
classes already inherit from a base class (other than
Object), thus preventing the
addition of polymorphic functionality through an abstract or concrete base class.
In a second situation, you need to add polymorphic functionality to a structure.
Abstract or concrete classes cannot be used to add polymorphic functionality to a
structure.
Solution
In these circumstances, as opposed to those explored in Recipe 3.4, implement poly-
morphism using an interface instead of an abstract or concrete base class. The code
shown here defines two different classes that inherit from
List<T>:
public class InventoryItems<T> : List<T>
{
// ...
}
public class Personnel<T> : List<T>
{
// ...
}
You want to add the ability to print from either of these two objects polymorphi-
cally. To do this, create an interface called
IPrint that defines a Print method to be
implemented in a class:
public interface IPrint
{
void Print( );
}
Implementing the IPrint interface on the InventoryItems<T> and Personnel<T>
classes gives you the following code:
public class InventoryItems<T> : List<T>, IPrint
{
public void Print( )
{
foreach (T obj in this)
{