论坛首页 入门技术论坛

static 类型初始化

浏览 1437 次
该帖已经被评为新手帖
作者 正文
   发表时间:2008-07-30  
OO
在初始化时,先初始化static类型变量,再初始化普通变量,再初始化构造函数。
如下程序:
class A{
A(int i){
System.out.println("A "+i);
}
void f(int i){
System.out.println("f1 "+i);
}
}

class B{
static A a1=new A(1);
B(){
System.out.println(" B ");
a2.f(1);
}
void f2(int i){
System.out.println(" f2 "+i);
}
static A a2=new A(2);
}

class C{
            A a3=new A(3);
static A a4=new A(4);
C(){
System.out.println(" C ") ;
a4.f(2);
}
void f3(int i){
System.out.println(" f3 "+i);
}
static A a5=new A(5);
}
public class TestStaticInitial {
public static void main(String args[]){
System.out.println("Now begin to test!");
new C();
System.out.println("Now begin to test the second time!");
new C();
bb.f2(1);
cc.f3(1);
}
static B bb=new B();
static C cc=new C();
}
执行顺序:
在主程序中,先初始化static 变量bb,cc.
再打印Now begin to test!;
执行new C();
再打印Now begin to test the second time
执行new C();

初始化变量bb的过程:
先初始化static 变量a1,a2
再执行B();

注意static变量只执行初始化一次

论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics