码迷,mamicode.com
首页 > 编程语言 > 详细

Java初始化顺序

时间:2014-08-20 22:48:03      阅读:274      评论:0      收藏:0      [点我收藏+]

标签:java   io   数据   ar   new   on   c   table   

1、在类的内部,变量的定义的先后顺序决定了初始化顺序,即使变量定义散布于方法定义间,他们仍旧会在任何方法(包括构造器)被调用之前得到初始化

2、静态数据的初始化

class Bowl{
Bowl(int marker){
print("Bowl("+marker+")");
}
void f1(int marker){
print("f1("+marker+")");
}

class Table{
static Bowl bowl1=new Bowl(1);
Table(){
print("Table()");
bowl2.f1(1);
}
void f2(int marker){
print("f2("+marker+")");
}
static Bowl bowl2=new Bowl(2);
}
}

class Cupboard{
Bowl bowl3=new Bowl(3);
static Bowl bowl4=new Bowl(4);

Cupboard(){
print("Cupboard()");
bowl4.f1(2);
}
void f3(int marker){
print("f3("+marker+")");
}
static Bowl bowl5=new Bowl(5);
}

public class StaticInitialization{
public static void main(String args[]){
print("Creating new Cupboard() in main");
new Cupboard();
print("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)


3、显式的静态初始化

class Cup{
Cup(int marker){print("Cup("+marker+")");}
void f(int marker){print("f("+marker+")");}
}

class Cups{
static Cup cup1;
static Cup cup2;
static {
cup1=new Cup(1);
cup2=new Cup(2);
}

Cups(){
print("Cups()");
}

public class ExlicitStatic{
public static void main(String args[]){
print("Inside main()");
Cups.cup1.f(99);   //(1)
}

//static Cups cup1=new Cup();  //(2)
//static Cups cup2=new Cup();  //(2)
}
}

output:

Cup(1)

Cup(2)

f(99)


Java初始化顺序,布布扣,bubuko.com

Java初始化顺序

标签:java   io   数据   ar   new   on   c   table   

原文地址:http://blog.csdn.net/zerountao/article/details/38712011

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!