Saturday, 18 June 2016

static and instance init. block

Init. block is located in the class body, could be anywhere.

Static initialize block: used for init. static variables; it will be invoked as class loaded. One class could have several static init. blocks. they will be invoked by the sequence in the body.

static {
//whatever code here
}


Instance initialize block: used for init. instance variables, and shared by the overloaded constructors. On compiling time, the instance init. block will be copied into each overloaded constructors. So static init. block is always invoked earlier than instance init. block.

{
//whatever code here
}



/**
 *
 * @author YNZ
 */
public class InitBlocks {

    static float sp;
    final static Integer[][] matrix = new Integer[2][3];
    Float[][] instMatrix = new Float[4][6];

    //static init block is a place to init satic field, 
    //as it cannot be done in one line.
    static {
        Random r = new Random();
        for (Integer[] matrix1 : matrix) {
            for (int j = 0; j < matrix1.length; j++) {
                matrix1[j] = r.nextInt(100);
            }
        }
    }

    {
        Random r = new Random();
        for (Float[] row : instMatrix) {
            for (int i = 0; i < row.length; i++) {
                row[i] = r.nextFloat();
            }
        }
    }

    InitBlocks() {
        //if static field can be modified in the instance. 
        sp = 20;
    }
    
    static  void printMatrix(T[][] mat){
        for(T[] row: mat){
            System.out.println(Arrays.toString(row));
        }
    }

    public static void main(String[] args) {
        printMatrix(InitBlocks.matrix);
        InitBlocks ib = new InitBlocks();
        printMatrix(ib.instMatrix);
    }
}


No comments:

Can Jackson Deserialize Java Time ZonedDateTime

Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...