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.
用途
- 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
- Static block(class initializer)
- [Java]--Java static keyword – Class, Method, Variable, Block, import
- Java – Static Class, Block, Methods and Variables
- static block
- block and static block
- Order of Java static initializer, insance initializer and reference object's initializer
- 应用程序启动速度优化Static Initializer
- Static Class (静态类)
- 静态代码块(static block)
- Static Class
- static Class
- static class
- static class
- static class
- Static class
- static class
- static class
- static class
- hihocoder 1089:403 Forbidden
- 初级cnn研究辅助:python的matplotlib显示图片 之 按钮和触发事件
- ResultSet总结
- ACM刷题之HDU————最少拦截系统(贪心)
- UVA10325 The Lottery(容斥原理)
- Static block(class initializer)
- 设计模式之迭代器模式
- Android学习(15) --在外部存储读写数据相关
- 前两年做了个三维重建程序
- java abstract类和interface的区别,精辟!
- Java注解
- Android学习(16) --获取sd卡剩余容量的代码
- hdu4059 The Boss on Mars(差分+容斥原理)
- [LeetCode]81. Search in Rotated Sorted Array II