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<T>{    private T data;    private Node<T> nextNode; // reference to next linked node    public Node(T data) { /* constructor body */ }    public void setData(T data) { /* method body */ }    public T getData() { /* method body */ }    public void setNext(Node<T> next) { /* method body */ }    public Node<T> getNext() { /* method body */ }}

has two private instance variables—data (of the generic type T) and Node<T> variable nextNode. Variable nextNode references a Node<T> object, an object of the same class being declared ...

Get Java™ How To Program (Early Objects), Tenth 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.