24.3. Self-Referential ClassesAself-referential class contains a reference member that refers to an object of the same class type. For example, the class declaration in Fig. 24.1 defines the shell of a self-referential class named Node. This type has two Private instance variablesInteger dataValue and Node reference nextNodeReference. Member nextNodeReference references an object of type Node, an object of the same type as the one being declared herethus the term "self-referential class." Member nextNodeReference is referred to as a link (i.e., nextNodeReference can be used to "tie" an object of type Node to another object of the same type). Class Node also has two propertiesone for instance variable dataValue (named Data) and another for instance variable nextNodeReference (named NextNode). Figure 24.1. Self-referential Node class declaration skeleton.
Self-referential objects can be linked together to form useful data structures, such as lists, queues, stacks and trees. Figure 24.2 illustrates two self-referential objects linked together to form a linked list. A backslash (representing a Nothing reference) is placed in the link member of the second self-referential object to indicate that the link does not refer to another object. A Nothing reference normally indicates the end of a data structure. Figure 24.2. Self-referential class objects linked together.
Creating and maintaining dynamic data structures requires dynamic memory allocationa program's ability to obtain more memory space at execution time to hold new nodes and to release space no longer needed. As you learned in Section 9.9, Visual Basic programs do not explicitly release dynamically allocated memoryrather, Visual Basic performs automatic garbage collection. The New operator is essential to dynamic memory allocation. New takes as an operand the type of the object being dynamically allocated and returns a reference to an object of that type. For example, the statement Dim nodeToAdd As New Node(10) allocates the appropriate amount of memory to store a Node and stores a reference to this object in nodeToAdd. If no memory is available, New throws an OutOfMemoryException. The constructor argument 10 specifies the Node object's data. The following sections discuss lists, stacks, queues and trees. These data structures are created and maintained with dynamic memory allocation and self-referential classes. |