网站首页 新闻首页 网页设计图形动画软件编程网站开发办公软件操作系统数据库网络技术认证考试范文资料黑客攻防 书籍教程 进入论坛

學習筆記:java初始化順序

http://www.diybl.com/ 2007-2-6  网络 点击:  [ 评论 ]
文章搜索:    【点击打包该文章】

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()就可以(需要了解重載)



如果图片或页面不能正常显示请点击这里 站内搜索:   

文章评论

请您留言