Data Structures and Algorithms
with Object-Oriented Design Patterns in C# |
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 , the ComparableObject class implements the IComparable interface discussed in Section .
The CompareTo method is defined as an abstract method in Program . Program 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.
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.