17.4. 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 variables—integer data and Node reference nextNode. Field nextNode references a Node object, an object of the same class being declared here—hence, the term “self-referential ...

Get Java™ How to Program, Seventh Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.