It is possible for two different reference variables to point to the same object.
When an object is no longer pointed to by any reference variable (including references stored deep inside the runtime or class library) it will be marked for garbage collection.
For example, the following program declares two TwoDPoint reference variables, creates one two-d point object, and assigns that object to both variables. The two variables are equal.
class EqualPointPrinter {
public static void main(String[] args) {
TwoDPoint origin1; // only declares, does not allocate
TwoDPoint origin2; // only declares, does not allocate
// The constructor allocates and usually initializes the object
origin1 = new TwoDPoint();
origin2 = origin1;
// set the fields
origin1.x = 0.0;
origin1.y = 0.0;
// print
System.out.println(
"origin1 is at " + origin1.x + ", " + origin1.y);
System.out.println(
"origin2 is at " + origin2.x + ", " + origin2.y);
} // end main
} // end EqualPointPrinter
origin1
and origin2
are two different
reference variables referring to the same point object.