Java的初始化类、变量、程序块加载探讨
时间:2011-03-20 zhangjunhd
1.基本类型数据的初始值
InitialValues.java
public class InitialValues {
boolean t;
char c;
byte b;
short s;
int i;
long l;
float f;
double d;
void print(String s) {
System.out.println(s);
}
void printInitialValues() {
print("boolean " + t);
print("char " + c);
print("byte " + b);
print("short " + s);
print("int " + i);
print("long " + l);
print("float " + f);
print("double " + d);
}
public static void main(String[] args) {
InitialValues iv = new InitialValues();
iv.printInitialValues();
}
}
结果:
boolean false
char _
byte 0
short 0
int 0
long 0
float 0.0
double 0.0
2.变量初始化
在类的内部,变量定义的先后顺序决定了初始化的顺序。即使变量定义散布于方法定义之间,它们仍旧在任何方法(包括构造器)被调用之前得到初始化。看下面的代码:
OrderOfInitialzation.java(执行顺序在代码中已标出,按类标注,罗马字母标注主类中执行顺序。)
class Tag {
Tag(int marker) {
System.out.println("Tag(" + marker + ")");
}
}
class Card {
Tag t1 = new Tag(1);// Ⅰ①
Card() {
System.out.println("Card()");// Ⅰ④
t3 = new Tag(33);// Ⅰ⑤
}
Tag t2 = new Tag(2);// Ⅰ②
void f() {
System.out.println("f()");// Ⅱ⑥
}
Tag t3 = new Tag(3);// Ⅰ③
}
public class OrderOfInitialzation {
public static void main(String[] args) {
Card t = new Card();// Ⅰ
t.f();// Ⅱ
}
}
结果:
Tag(1)
Tag(2)
Tag(3)
Card()
Tag(33)
f()
Java的初始化类、变量、程序块加载探讨(2)
时间:2011-03-20 zhangjunhd
3.静态数据初始化
看下面的代码:
StaticInitialization .java
class Bowl {
Bowl(int marker) {
System.out.println("Bowl(" + marker + ")");
}
void f(int marker) {
System.out.println("f(" + marker + ")");
}
}
class Table {
static Bowl b1 = new Bowl(1);// Ⅰ①
Table() {
System.out.println("Table()");// Ⅰ③
b2.f(1);// Ⅰ④
}
void f2(int marker) {
System.out.println("f2(" + marker + ")");
}
static Bowl b2 = new Bowl(2);// Ⅰ②
}
class Cupboard {
Bowl b3 = new Bowl(3);// Ⅱ③,Ⅳ①,Ⅵ①
static Bowl b4 = new Bowl(4);// Ⅱ①
Cupboard() {
System.out.println("Cupboard");// Ⅱ④,Ⅳ②,Ⅵ②
b4.f(2);// Ⅱ⑤,Ⅳ③,Ⅵ③
}
void f3(int marker) {
System.out.println("f3(" + marker + ")");
}
static Bowl b5 = new Bowl(5);// Ⅱ②
}
public class StaticInitialization {
public static void main(String[] args) {
System.out.println("Creating new Cupboard() in main");// Ⅲ
new Cupboard();// Ⅳ
System.out.printl
|