JAVA:初始化静态数据

  • Post author:
  • Post category:java



无论创建多少个对象,静态数据都只占用一份存储区域,static 关键字不能应用于局部变量,因此它只作用于域。如果域是静态的基本类型域,且也没有对它进行初始化,那么它就会获得基本类型的标准值;如果是一个对象的引用,默认初始值为Null;

初始化顺序参照下面例子,类名StaticInitialization:

class Bowl{
    Bowl(int marker){
        System.out.println("Bowl("+marker+")");
    }
    void f1(int marker){
        System.out.println("f1("+marker+")");
    }
}
class Table{
    static Bowl bowl1=new Bowl(1);
    Table(){
        System.out.println("Table()");
        bowl2.f1(1);
    }
    void f2(int marker){
        System.out.println("f2("+marker+")");
    }
    static Bowl bowl2= new Bowl(2);
}
class Cupboard{
    Bowl bowl3=new Bowl(3);
    static Bowl bowl4=new Bowl(4);
    Cupboard(){
        System.out.println("Cupboard()");
        bowl4.f1(2);
    }
    void f3(int marker){
        System.out.println("f3("+marker+")");
    }
    static Bowl bowl5= new Bowl(5);
}

public class StaticInitialization {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println("Creating new Cupboard() in main");
    new Cupboard();
    System.out.println("Creating new Cupboard() in main");
    new Cupboard();
    table.f2(1);
    cupboard.f3(1);
}
static Table table= new Table();
static Cupboard cupboard=new Cupboard();

}
/* Output:
Bowl(1)
Bowl(2)
Table()
f1(1)
Bowl(4)
Bowl(5)
Bowl(3)
Cupboard()
f1(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f1(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f1(2)
f2(1)
f3(1)

*///:~



版权声明:本文为qq_38333529原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。