Passing “this” in java constructor

后端 未结 9 714
梦毁少年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 12:04

    public class ClassA {
        private boolean ClassAattr = false;
            public ClassA() {    
            ClassAHandler handler = new ClassAHandler(this);
            classAttr = true;
        }
    }
    
    public class ClassAHandler extends GeneralHandler {
        ClassA ca = null;
    
        public ClassAHandler(ClassA classa) {
            this.ca = classa;
            System.out.println(ca.classAttr);
        }
    }
    

    So I have added the statement classAttr = true;

    The System.out.println statement will print false. This is because the construction of ClassA was not complete at that point.

    So my suggestion is to add another method in classA which will create the ClassAHandler and then the classAHandler will receive fully constructed ClassA object

    So that the code will look like.

    public class ClassA {
        private boolean ClassAattr = false;
    
        public ClassA() {    
    
            classAttr = true;
        }
    
        public init() {
            ClassAHandler handler = new ClassAHandler(this);
        }
    }
    

    So that the code sequence will be new ClassA().init() and will work perfectly

提交回复
热议问题