Passing “this” in java constructor

后端 未结 9 732
梦毁少年i
梦毁少年i 2020-11-30 11:39

Look into the following code:

public class ClassA {
    private boolean ClassAattr = false;

    public ClassA() {    
        ClassAHandler handler = new Cl         


        
9条回答
  •  鱼传尺愫
    2020-11-30 11:39

    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).

提交回复
热议问题