21.2 Self-Referential Classes

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

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

has two private instance variables—data (of the generic type E) and Node<E> variable nextNode. Variable nextNode references a Node<E> object, an object of the same class being declared here—hence the term “self-referential class.” ...

Get Java How to Program, Early Objects, 11th 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.