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 block
a: 100
Call common part
Call constructor with no parameter
Call common part
Call 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.
用途
- Set DB connnection
- API init
- 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