Look into the following code:
public class ClassA {
private boolean ClassAattr = false;
public ClassA() {
ClassAHandler handler = new Cl
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
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;
}
}
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