Java - static initialization -



Java - static initialization -

i have written piece of code :

public class child{ int y ; private static final int z = getz(); static { system.out.println("the value of z "+z); } public int getx(){ system.out.println("get x"); homecoming 10; } public int gety(){ kid ch = new child(); system.out.println("get y"); ch.y = getx(); homecoming y; } public static int getz(){ system.out.println("get z"); homecoming new child().gety(); } public child(){ system.out.println("child constructor"); } public static void main(string...args){ kid ch = new child(); system.out.println("the value of z in main "+z); } }

and output :

get z kid constructor kid constructor y x value of z 0 kid constructor value of z in main 0

can please explain me why value of z 0 , not 10 ?

edit:- , got reply first question . still have uncertainty , far know static blocks executed after class loaded , before first object of class instantiated . sop("the value of z "+z) should have been executed before sop("child constructor") ! ain't ?

look @ gety():

public int gety(){ kid ch = new child(); system.out.println("get y"); ch.y = getx(); homecoming y; }

the first 3 lines irrelevant - don't alter value of y in this instance, gets returned.

you're creating awful lot of pointless objects in frankly spaghetti code, called while initializing same class you're constructing instances of. suggest seek maintain code lot simpler this. static initializers should avoided possible start with, allow lone ones go round houses no useful work.

java static static-initialization compile-time-constant

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -