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.
Can an object contain a reference to another object of the same class as itself?
Sure. Objects can be designed to do this.
Examine the following Java class:
public class Node { private Node next; private int value; // Constructor. Make a Node containing val. // Initialize next to null public Node ( int val ) { value = val; next = null; } public int getValue() { return value; } // get the value in this Node public Node getNext() { return next; } // get a pointer to another Node 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 program that uses the class:
public class NodeTester { public static void main ( String[] args ) { Node node0 = new Node( 223 ); System.out.println("Node 0: " + node0 ); } }
The program constructs a Node
object and puts a reference to in in node0
.
The member next
is of type Node
(ie. a potential reference to another Node
object).
The slash in next
represents the null
put there by the constructor.
What is the output of the program?
Reminder:
+
means string concatenation.Another Reminder: string concatenation invokes the
toString()
method of the object.