java - Difference between class variable initializers , static initializers of the class, and the field initializers -


i trying follow jvm specs http://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.4.2. frustrating me read unclear specs. so: differences between:

  • class variable initializers

  • static initializers of class

  • field initializers

/* initalizers */

class {      private static string x = "sfi";  //static field initializer     private string ifi = "ifi";  //instance field initializer      static {              //static (block) initalizer ?!         string y = "sbi";     }      {                    //instance (block) initalizer ?!          string z = "ibi";     } } 

static members

first need understand difference between static , non-static fields of class. static field not bound instance of class, property of class (that reason why access them through class) in example can access x whithin a this: a.x. common example counting number of objects class has:

private static int counter = 0; public a() {     counter++;   }  // instance count  public static int getcounter()  {     return counter; } 

this method call somewhere else this: a.getcounter() , retrieve number of objects have type a.

non-static members

these variables specific each object (instance) of class. in example sfi. runtime system guarantees sfi available whenever object of type a created , have default value of ifi, difference here each object create have member called sfi default value of ifi each object can later modify of course.

initializing blocks

they feature designed used when initialization cannot done inline (initialization requires more complex logic for loop or error-checking). here again have:

static { /* init code ... /* } 

which static initialization block "can appear anywhere in class body. runtime system guarantees static initialization blocks called in order appear in source code" - here

if, on other hand, we want initialize instance members cannot in 1 line can use block without static keyword:

{   // init code instance members } 

the java compiler copies initializer blocks every constructor. therefore, approach can used share block of code between multiple constructors.


Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -