Passing “this” in java constructor

Passing this to another method/object from inside the constructor can be rather dangerous. Many guarantees that objects usually fulfill are not necessarily true, when they are looked at from inside the constructor.

For example if your class has a final (non-static) field, then you can usually depend on it being set to a value and never changing.

When the object you look at is currently executing its constructor, then that guarantee no longer holds true.

As an alternative you could delay the construction of the ClassAHandler object until it is first needed (for example by doing lazy initialization in the getter of that property).

Leave a Comment