GregSmith said:
yes - a constructor is only slightly more special than any other method
yes - "this" exists within the constructor. however, some stylists
claim that "this" isnt completely defined until the constructor is
complete
The reason being that you have to be careful using "this" in the
constructor. When you do, you may under _NO_ condition leak it out. (A
method could for example register the "instance" which in reality isn't
completely instantiated yet, somwhere else and another thread picks it up
-- and all hell breaks lose).
It is perfectly valid to use this in the constructor and things like
class foo {
private int field;
public foo(int field) {
this.field = field;
}
}
are common and not bad at all nor dangerous. However, do not leak the
"this" and follow all execution paths so you are sure that specific "this"
is never used outside this class until the constructor has finished.
Or to put it in another way: "this" or rather the object it points to is in
an undefined state when accessed from *another thread* while the
constructor is still running. This can have the side effect that while
everything is initialized within the object and the constructor is just
about to exit, another thread who accesses the same instance via the this
reference it got somehow, may see a completely empty/uninitialized object.
It may run perfectly well on a single-processor system but fail every time
on a multiprocessor system due to memory caching effects.
In short: just don't leak it and watch out if you're going to assign it to
some public static variable. Otherwise you can't IMHO do anything wrong
with it.
CU
Rene