Self-Referential Classes

A self-referential class contains an instance variable that refers to another object of the same class type. For example, the declaration

class Node { private int data; private Node nextNode; // reference to next linked node public Node( int data ) { /* constructor body */ } public void setData( int data ) { /* method body */ } public int getData() { /* method body */ } public void setNext( Node next ) { /* method body */ } public Node getNext() { /* method body */ } } // end class Node

declares class Node, which has two private instance variablesinteger data and Node reference nextNode. Field nextNode references a Node object, an object of the same class being declared herehence, the term "self-referential class." Field nextNode is a linkit "links" an object of type Node to another object of the same type. Type Node also has five methods: a constructor that receives an Integer to initialize data, a setData method to set the value of data, a getdata method to return the value of data, a setNext method to set the value of nextNode and a getNext method to return a reference to the next node.

Programs can link self-referential objects together to form such useful data structures as lists, queues, stacks and trees. Figure 17.1 illustrates two self-referential objects linked together to form a list. A backslashrepresenting a null referenceis placed in the link member of the second self-referential object to indicate that the link does not refer to another object. Note the backslash is illustrative; it does not correspond to the backslash character in Java. Normally, a null reference indicates the end of a data structure. There are other ways to represent the end of a data structure that are beyond the scope of this text.

Figure 17.1. Self-referential-class objects linked together.

Категории