Re: Simple question about instantiating
Roy Gourgi wrote:
Hi Eric,
Is the constructor also only for the class (almost like a static method)
that is run each time an object is instantiated? And if that is the case,
then all the 10 objects that are created really have nothing in them because
the class variable belongs to the class, the constructor also belongs to the
class and finally also the public static int getInstanceCount() method?
Correct me if I am wrong.
Every class, directly or indirectly, extends java.lang.Object, so every
object, including each CountTest, has all the instance methods declared
for Object. That said, as the name implies, a CountTest does not seem to
have any use of its own. As the name implies, it appears to exist only
to demonstrate the ability to count instance creation events.
When a constructor runs it is associated with a particular instance, and
"this" means the same as it would in a non-static method. In that way,
it is more like a non-static method than a static method. On the other
hand, unlike a static method, you don't need an existing instance of the
class to invoke it.
It is best to think of a constructor as just being a constructor,
without the static/non-static distinction that applies to fields and method.
One final question is in main there is the instantiation statement:
CountTest c1 = new CountTest();
because this statement is in a for loop that runs 10 times, would the c1
reference variable not point to only the last object (i.e. 10th object)
because each time that it is initialized it points to the last object?
At least in theory, a c1 appears each time the loop body is executed,
references the CountTest that was created by its initializer, and ceases
to exist at the end of that execution of the loop body. The c1 that
existed during the first iteration pointed to the first CountTest. The
c1 that existed during the second iteration pointed to the second
CountTest...
Patricia