go to previous page   go to home page   go to next page

Answer:

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.

Node

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:

one node, not linked

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.


QUESTION 2:

What is the output of the program?

Reminder: + means string concatenation when one used with a string.

Another Reminder: node0 invokes the toString() method of the object when involved with string concatenation.