Static block(class initializer)

来源:互联网 发布:面向对象编程原则 编辑:程序博客网 时间:2024/06/13 22:56

static block static {}

The code inside static block is executed only once: the first time you make an object of that class or the first time you access a static member of that class (even if you never make an object of that class,actually, when class is resolved).

initializer block {}

initializer block contains the code that is always executed whenever an instance is created. It is used to declare/initialize the common part of various constructors of a class.

An xample

package com.practice.staticblock;public class TestStaticBlock {    private static final int a;    //static block    static {        System.out.println("Call static block");        a = 100;    }    //initializer block    {        System.out.println("Call common part");    }    public TestStaticBlock() {        System.out.println("Call constructor with no parameter");        // TODO Auto-generated constructor stub    }    public TestStaticBlock( int a ) {        System.out.println("Call constructor with parameter");        // TODO Auto-generated constructor stub    }    public static void main(String[] args) {        // TODO Auto-generated method stub        System.out.println("a: " + TestStaticBlock.a);        new TestStaticBlock();        new TestStaticBlock(100);    }}

Output:

Call static blocka: 100Call common partCall constructor with no parameterCall common partCall constructor with parameter

约束

A block of code static { ... } inside any java class. and executed by virtual machine when the class is called or instantiated.
1. No return statements are supported.
2. No arguments are supported.
3. No this or super are supported.

用途

  1. Set DB connnection
  2. API init
  3. logging

总结

  • static block is executed ONLY once
  • static block is executed BEFORE constructor
  • Initializer block is executed whenever a class being instantiated
  • Initializer block is always executed BEFORE constructor

Refer to: static block in java

0 0
原创粉丝点击