1: Some wording: We don't instantiate objects at all, we instantiate classes, and the product of a class instantiation is an object (also called an instance). Of course we can instantiate a class as many times as required to create a new and different object with each instantiation.
2: Whatever, you cannot have the code you suggest:
Test test = new Test();
Test test = new Test();
neither you can have this:
for (i=0; i<3; i++) {
Test test = new Test();
Test test = new Test();
}
None will compile, because the part Test test
is the declaration of variable test
(of type Test
), and no language, including Java, allows to declare twice the same variable in the same scope.
However you may assign multiple times the same variable (as the name implies), with different objects, like this:
Test test = new Test();
test = new Test();
The first line declares test
and assign it an object newly created. The second line assign to test
another object, also newly created.
Also note that shortcuts are allowed in Java:
for (i=0; i<3; i++) {
Test test = new Test();
}
This loop will not declare test
3 times. It is understood as assigning three new different objects in sequence to the variable test
which will be declared only once. (compare with the previous loop).
3: What happens to the variable test
, and to the two objects of type Test
?
The variable test
is first assigned the reference of an object, then of another object. A variable retains only the last reference assigned.
The first object of type Test
is not assigned to test
anymore. If no other variable has been assigned its reference, then this object cannot be accessed in any way by the program, and thus is useless. It is made eligible to garbage collection by the system. At some point in time the system (the JVM) will run its garbage collector which will clear it from memory.
The second object will live as long as at least one variable references it, then the garbage collector will also take care of it and bring it to the Unreferenced Objects Cemetery. That's the true life of Java objects :-(