Can several objects of the same Class exist in a program at the same time?
Yes. Of course, to get to 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 println 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 println its data. System.out.println( strA ); // follow reference to first // object and println 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 object becomes garbage
(until the program has finished running.)