static变量初始化 静态块
2017-02-16 21:36
204 查看
static初始化只有在必要的时候才会进行。如果不创建一个 Table 对象,而且永远都不引用Table.b1 或Table.b2,那么 static Bowl b1 和b2 永远都不会创建。然而,只有在创建第一个Table 对象之后(或者发生了第一次static 访问),它们才会创建。在那以后,static 对象不会重新初始化。初始化的顺序是首先static(如果它们尚未由前一次对象创建过程初始化),接着是非static 对象。
class Table {
static Bowl b1 = new Bowl(1);
Table() {
System.out.println("Table()");
}
void f2(int marker) {
System.out.println("f2(" + marker + ")");
}
static Bowl b2 = new Bowl(2);
}
下属的这段代码仅执行一次——首次生成那个类的一个对象时,或者首次访问属于那个类的一个 static 成员时(即便从未生成过那个类的对象)。
class Spoon {
static int i;
static {
i = 47;
}
Cup(2)
Cups()
Cups()
Inside main()
f(99)
以上代码来自thinkinJava
输出这个结果是因为,现走类中的static变量,然后走方法,cups调用静态变量的时候会走cups的static静态块,输出1,2,然后输出空,第二次new一个y的时候静态块直走一次,所以1,2不生成了,所以再打印一个空,再继续走system
class Table {
static Bowl b1 = new Bowl(1);
Table() {
System.out.println("Table()");
}
void f2(int marker) {
System.out.println("f2(" + marker + ")");
}
static Bowl b2 = new Bowl(2);
}
下属的这段代码仅执行一次——首次生成那个类的一个对象时,或者首次访问属于那个类的一个 static 成员时(即便从未生成过那个类的对象)。
class Spoon {
static int i;
static {
i = 47;
}
package demo; class Cup { Cup(int marker) { System.out.println("Cup(" + marker + ")"); } void f(int marker) { System.out.println("f(" + marker + ")"); } } class Cups { static Cup c1; static Cup c2; static { c1 = new Cup(1); c2 = new Cup(2); } Cups() { System.out.println("Cups()"); } } public class ExplicitStatic { public static void main(String[] args) { System.out.println("Inside main()"); Cups.c1.f(99); // (1) } static Cups x = new Cups(); // (2) static Cups y = new Cups(); // (2) }Cup(1)
Cup(2)
Cups()
Cups()
Inside main()
f(99)
以上代码来自thinkinJava
输出这个结果是因为,现走类中的static变量,然后走方法,cups调用静态变量的时候会走cups的static静态块,输出1,2,然后输出空,第二次new一个y的时候静态块直走一次,所以1,2不生成了,所以再打印一个空,再继续走system
相关文章推荐
- static 成员变量 初始化问题
- 从static变量初始化到Spring/Spring boot的工具类静态变量注入
- Cocos2dx static变量的声明和初始化
- C++ static、const和static const类型成员变量声明以及初始化
- Static和Final修饰类属性变量及初始化(转载)
- Java的static修饰变量,方法,代码块的初始化顺序
- 类中常量、static变量、static常量的初始化
- C++ static、const和static const类型成员变量声明以及初始化
- static 变量初始化问题
- 初始化一个static的Map变量
- java中static变量只能初始化一次
- c++ 类中static变量初始化问题
- Static和Final修饰类属性变量及初始化
- C++ 模板类中的static变量和函数 初始化
- C++常量折叠和类中const、static成员变量初始化
- 关于全局、static对象/变量的初始化问题
- java学习笔记 类初始化 调用static变量是否会初始化
- String、StringBuffer、StringBuilder区别,HashMap与HashTable区别,final关键字详解及初始化成员变量位置,static关键字详解,抽象类与接口区别
- Static和Final修饰类属性变量及初始化
- 关于static成员变量的初始化的实验