oop - Why am I getting two different outputs in Java code -
class { int xyz = new b().show(); // prints c=0 , 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; } } } class c { public static void main(string args[]) { p = new a(); } }
why getting c=0
, c=-319
later. similarly, why z null
, after not null
. happening in code?
you need know new
operator responsible creating empty instance of class (instance fields have default values: numeric:0
; boolean:false
, char:'\0'
, reference:null
). code of constructor invoked after new
finish job, , responsible setting correct state such empty object.
now initialization of fields happens in constructor, code
class { int xyz = new b().show(); // prints c=0 , 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 same (notice default values)
class { 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
xyz = this.new b().show();
so created instance of b
have access instance of a
initialized in current a
constructor. code initialized b
, z
int c = -319; b z = new b();
happens after first show()
method (which uses b
, z
) means default values shown.
this problem doesn't exist in case of second show()
lmn = z.show();
because b
, z
initialized.
Comments
Post a Comment