java - Subclass final static initialization prior to superclass class intialization? -


i couldn't find specific post referring specific case, i'd ask think yes/no question.

here's jls §12.4.2 (java se 8), listing 6-7:

  1. [...] then, initialize static fields of c constant variables (§4.12.4, §8.3.2, §9.3.1).
  2. next, if c class rather interface, , superclass has not yet been initialized, let sc superclass [...] each s in list [ sc, si1, ..., sin ], recursively perform entire procedure s. if necessary, verify , prepare s first. [...]

my question: mean final static variable of subclass initialized before static initialization of superclass (assuming final static initialized part of declaration)?

the answer might so. key part constant word meaning.

consider code

class foo {     public static final int foo_value = 1000;      static {         system.err.println("foo bar.bar_value=" + bar.bar_value);     } }  class bar extends foo {     public static final int bar_value = 2000;      static {         system.err.println("bar foo.foo_value=" + foo.foo_value);     } } 

the output of program be

foo bar.bar_value=2000 bar foo.foo_value=1000 

in case bar static final variables initialized before foo static initialization. both foo_value , bar_value constants javac may inline fields.

but can trick compiler pretending final variable not constant in way

class foo {     public static final int foo_value = integer.valueof(1000).intvalue();      static {         system.err.println("foo " + bar.bar_value);     } }  class bar extends foo {     public static final int bar_value =  integer.valueof(2000).intvalue();      static {         system.err.println("bar " + foo.foo_value);     } } 

and output be

foo bar.bar_value=0 bar foo.foo_value=1000 

so foo static initializer finished before static final bar.bar_value initialized.


Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -