Can several objects of the same class exist in a program at the same time?
Yes. Of course, to locate each one, each must have a reference.
Here is another version of the example program:
class EgString4 { public static void main ( String[] args ) { String strA; // reference to the first object String strB; // reference to the second object strA = new String( "The Gingham Dog" ); // create the first object and // Save its reference. System.out.println( strA ); // follow reference to first // object and print its data. strB = new String( "The Calico Cat" ); // create the second object and // Save its reference. System.out.println( strB ); // follow reference to second // object and print its data. System.out.println( strA ); // follow reference to first // object and print its data. } }
This program has TWO reference variables, strA
and strB
.
It creates two objects and places each reference in one of the variables.
Since each object has its own reference variable,
no reference is lost, and no objects become garbage
(until the program has finished running).
What will this program print to the monitor?