Data Structures and Algorithms with Object-Oriented Design Patterns in C#
next up previous contents index

Abstract Comparable Objects

The abstract class at the top of the class hierarchy is called ComparableObject. All the other classes in the hierarchy are ultimately derived from this class. As shown in Figure gif, the ComparableObject class implements the IComparable interface discussed in Section gif.

The CompareTo method is defined as an abstract method in Program gif. Program gif also defines the private method Compare. To understand the operation of the Compare method, consider an expression of the form obj1.Compare(obj2). First, the Compare method determines whether obj1 and obj2 are instances of the same type (line 7). If they are, the CompareTo method is called to do the comparison. Thus, the CompareTo method is only ever invoked for instances of the same class.

   program4349
Program: ComparableObject methods.

If obj1 and obj2 are instances of different types, then the comparison is based on the names of the types (lines 10-11). Suppose obj1 is an instance of the class named Opus6.StackAsArray and obj2 is an instance of the class named Opus6.QueueAsLinkedList. Then obj1 is ``less than'' obj2 because StackAsArray precedes alphabetically QueueAsLinkedList.


next up previous contents index

Bruno Copyright © 2001 by Bruno R. Preiss, P.Eng. All rights reserved.