Reputation: 1124
here is my problem
class A{
private B b = new B(this); // line 2
A(){}
}
This is just an ex. code and works fine. But i have a doubt about this
is used to current reference (instance of A). Class initializing happens before to get a class instance. So how can we put this
in line 2. i asked does instantiation happen before initializing?
Upvotes: 0
Views: 89
Reputation: 7706
You bring up an interesting point. Here is a contrived instructional example that demonstrates a run time problem that can happen when using your example.
class A {
private boolean isInitialized = false;
private final B b = new B(this);
public A() {
initialize();
}
private void initialize() {
isInitialized = true;
}
public boolean isInitialize() {
return isInitialized;
}
public B getB() {
return b;
}
}
class B {
private boolean isInitialized = false;
final private A a;
public B(final A a) {
this.a = a;
initialize();
System.out.println("inB: a.isInitialize()=" + a.isInitialize());
}
private void initialize() {
isInitialized = true;
}
public boolean isInitialize() {
return isInitialized;
}
}
public static void main(final String[] args) {
final A a = new A();
System.out.println("inMain: a.isInitialize()=" + a.isInitialize());
System.out.println("inMain:a.getB().isInitialize()=" + a.getB().isInitialize());
}
Output:
inB: a.isInitialize()=false
inMain: a.isInitialize()=true
inMain:a.getB().isInitialize()=true
Using the passed reference to class A within class B runs the real risk of using an object that is not fully initialized.
Be careful.
Upvotes: 2
Reputation: 10553
this
will show its existence when you create an object of class A. Instance variable are assigned after object creation and static variable are initialize as soon as class loads and also before creations of any object.
you cannot use above initialization in static block
static {
private B b = new B(this); // compiler error. you cannot use 'this' in static context.
}
Upvotes: 0
Reputation: 15173
This is not class initialization (try to debug new ClassA()
step by step), it is actually instance initialization.
There can be some problems if the constructor (from ClassB
) calls some functions from ClassA
, which access some fields in ClassA
that are not initialized.
Edit: this is done before the constructor is called.
Upvotes: 1
Reputation: 1042
No need for changes, everything is fine. this
is a valid reference to A.
Upvotes: 0
Reputation: 1048
this
is used correctly. The constructor doesn't need to be called at all.
Upvotes: 0