当前位置导航:炫浪网>>网络学院>>网页制作>>JSP教程

學習筆記:java初始化順序

class Bowl {
Bowl(int marker) {
System.out.println("Bowl(" + marker + ")");
}

void f1() {
System.out.println("Ok");
}
}

class Cupboard {
Bowl b1 = new Bowl(1);

static Bowl b2 = new Bowl(2);

Cupboard() {
System.out.println("Cupboard()");
}

static Bowl b3 = new Bowl(3);
}

class Table {
Table() {
System.out.println("Table()");
}
Table(String a,int i){
this();
System.out.println("Ok");
}
}

public class Order {
static Cupboard t1 = new Cupboard();

static Table t2;

Bowl t3 = new Bowl(10);

void print() {
t3.f1();
}

public static void main(String[] args) {
System.out.println("Creating new Cupboard() in main");
new Cupboard();
System.out.println("Creating new Cupboard() in main");
Order od = new Order();
od.t3.f1();
Table t4 = new Table("aa",1);
}
}

程序運行時:裝載Order.class,運行Order類中的static塊
static Cupboard t1 = new Cupboard();
這構造了一個Cupboard對象,構造對象時,會裝載Cupboard類,
也是先執行static塊
static Bowl b2 = new Bowl(2);//創建一個Bowl對象,過程和Cupboard一樣,會調用構造函數
static Bowl b3 = new Bowl(3);//同上
然後執行
Bowl b1 = new Bowl(1);//創建一個Bowl對象
然後執行構造函數Bowl()

接下來:
static Table t2;//這只是聲明,並沒有創建對象,不用理會
然後:
執行main函數中的語句
System.out.println("Creating new Cupboard() in main");
new Cupboard(); //注意的是,static只會初始化一次
System.out.println("Creating new Cupboard() in main");
Order od = new Order();//創建Order對象,同上
od.t3.f1();
Table t4 = new Table("aa",1);//創建了Table,注意這裡構造函數的調用this()就可以(需要了解重載)



相关内容
赞助商链接