You need to know that new
operator is responsible for creating empty instance of class (instance with fields which will have default values: numeric:0
; boolean:false
, char:'\0'
, reference:null
). Code of constructor is invoked after new
will finish its job, and is responsible for setting up correct state for such empty object.
Now initialization of fields happens in constructor, so your code
class A {
int xyz = new B().show(); // prints c=0 and z=null
int c = -319;
B z = new B();
int lmn = z.show(); // prints c=-319
class B {
int show() {
System.out.println("c=" + c);
System.out.println("z=" + z);
return -555;
}
}
}
is is same as (notice default values)
class A {
int xyz = 0; //default values
int c = 0; //
B z = null; //
int lmn = 0; //
A(){
xyz = new B().show();
c = -319;
z = new B();
lmn = z.show();
}
class B {
int show() {
System.out.println("c=" + c);
System.out.println("z=" + z);
return -555;
}
}
}
Also
xyz = new B().show();
is same as
xyz = this.new B().show();
so created instance of B
will have access to instance of A
which is initialized in current A
constructor. BUT code which initialized b
and z
int c = -319;
B z = new B();
happens after your first show()
method (which uses b
and z
) which means that their default values will be shown.
This problem doesn't exist in case of second show()
lmn = z.show();
because now b
and z
are initialized.