Why does the order of static members in java matter? -


why order of static members in java matter?

e.g.

public class {   static int i= 1;   static int c = i;   int = c; <<------ ok } 

vs.

public class b {   int = c; <<--- compile error   static int c = 1;   static int = c; } 

why java designed such ordering makes difference? (i have edited question based on answer of ykaganovich)

edit: thank ! have tested examples non-static variables. has same behaviour, static doesn't play role here. question misleading (at least me). try summarize answers.

edit 2:

i try sum answers up. more info please read answers below :)

a) direct forward references in java as:

static int = c; static int c = 1; 

are confusing. it's not allowed in java. main reason initialisation order.

b) indirect forward references allowed in java

public class test { int = c(); int c() { return c; }   int c = 1; } 

c) must define order of execution of variable declaration (or initialisation), it's definition matter how this done in java. in java ordering top-to-bottom.

d) well-defined order provide way predictable results.

e) if design program not have issues.

even though can guess asking here, example code not demonstrate , wonder how nobody noticed that. have inspected entire revision history of question , haven't found single instance of program produce compiler error.

but, let me show example does produce compiler error may have in mind:

public class test {   int = c;   int c = 1; } 

what happens here reference c in initializer of i. therefore trying read variable hasn't been yet initialized. note has nothing declaration order (compile-time), initialization order (runtime). in java, in other similar languages, order of member declaration plays no role except in capacity of implying order of execution of member initializers.

java has check prevents 1 initializer reading variable initializer has not yet run. java has many other such checks because designed try hard protect programmer making silly mistakes. in words of james gosling, java meant "blue collar" language. should answer "why" question.

note specific compiler check discussing here quite weak , works obvious cases. consider simple variation on above program:

public class test {   int = c();   int c() { return c; }   int c = 1; } 

no errors produced here. java doesn't go far inspecting in method call initializer.


Comments

Popular posts from this blog

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -

java - JavaFX 2 slider labelFormatter not being used -