Can an object contain a reference to another object?
Of course. We have seen this many times. For example, objects frequently refer to String
objects.
Could an object contain a reference to another object of the same class as itself?
Sure. Objects of a particular class can be designed to refer to other objects of the same class.
Examine the following Java class:
public class Node { private Node next; private int value; public Node ( int val ) { value = val; next = null; } public int getValue() { return value; } public Node getNext() { return next; } public void setValue( int val ) { value = val; } public void setNext( Node nxt ) { next = nxt; } public String toString() { return value + ", "; } }
A Node
object holds an integer and an object reference.
For the moment, ignore the object reference.
Here is a picture of a Node
:
Here is a short driver program for the class:
public class NodeTester { public static void main ( String[] args ) { Node node0 = new Node( 223 ); System.out.println("Node 0: " + node0 ); } }
The picture shows the Node
object this program creates.
The member next
is declared to be of type Node
.
The slash in the member next
represents the null
.
What is the output of the program?
Reminder:
+
means string concatenation when one used with a string.Another Reminder:
node0
invokes thetoString()
method of the object when involved with string concatenation.