您的位置:首页 > 其它

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;

}

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: