Passing “this” in java constructor

后端 未结 9 688
梦毁少年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:54

    This page has a very good explanation of why letting the "this" reference escape is a bad idea:

    http://www.ibm.com/developerworks/java/library/j-jtp0618.html#2

    Check the "Don't publish the "this" reference during construction" section

    0 讨论(0)
  • 2020-11-30 11:59

    If I understand correctly, you need the handler to have a reference to ClassA, but you don't want to set this up from within the constructor of ClassA? If that is the case, then you could separate construction from "wiring up" using a factory pattern, which will prevent your ClassA from needing to know about the ClassAHandler class. Kind of like this:

    public class ClassA {
    
        private boolean ClassAattr = false;
    
        public ClassA() {
        }
    
    }
    
    
    public class ClassAHandler {
    
        private ClassA ca = null;
    
        public ClassAHandler(ClassA classa) {
            this.ca = classa;
        }
    
    }
    
    
    public HandlerFactory {
    
        public ClassAHandler createClassAHandler(ClassA classa) {
            ClassAHandler handler = new ClassAHandler(classa);
            return handler;
        }
    
    }
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题