局部变量如果没有初始化,比如:
成员变量如果没有初始化,比如:
如果在初始化时,引用了一个没有被初始化的变量(包括主数据类型和其他对象)也是不允许的。
编译器会提示找不到字符i
变量初始化的顺序是由变量在程序中的顺序决定的,变量先于方法初始化,由Thinking in java中的例子就可以看出来:
[img]/upload/attachment/93008/680ab717-2a63-3fb2-bedc-6420ecf91c9b.gif[/img]
初始化的顺序是首先static(如果它们尚未由前一次对象创建过程初始化),接着是非static 对象。
运行结果:
[img]/upload/attachment/93016/ae8649d6-f6dc-3450-bbe5-8aecab740e31.gif[/img]
class test {
static void f() {
int i;//未初始化局部变量
i++;
}
public static void main(String [] args) {
test t = new test();
t.f();
}
}
编译时会报错:未初始化局部变量
成员变量如果没有初始化,比如:
class test {
int i;//类成员变量可以不用初始化,系统有设置默认值
void prt() {
System.out.println(i);
}
public static void main(String [] args) {
test t = new test();
t.prt();
}
}
编译通过,运行时输出:0
如果在初始化时,引用了一个没有被初始化的变量(包括主数据类型和其他对象)也是不允许的。
class Test2 {
void f() {
int j =i;
int i = 0;
}
public static void main(String [] args) {
Test2 t2 = new Test2();
t2.f();
}
}
编译器会提示找不到字符i
变量初始化的顺序是由变量在程序中的顺序决定的,变量先于方法初始化,由Thinking in java中的例子就可以看出来:
class Tag {
Tag(int marker) {
System.out.println("Tag(" + marker + ")");
}
}
class Card {
Tag t1 = new Tag(1); // Before constructor
Card() {
// Indicate we're in the constructor:
System.out.println("Card()");
t3 = new Tag(33); // Re-initialize t3
}
Tag t2 = new Tag(2); // After constructor
void f() {
System.out.println("f()");
}
Tag t3 = new Tag(3); // At end
}
public class OrderOfInitialization {
public static void main(String[] args) {
Card t = new Card();
t.f(); // Shows that construction is done
}
}
运行结果:
[img]/upload/attachment/93008/680ab717-2a63-3fb2-bedc-6420ecf91c9b.gif[/img]
初始化的顺序是首先static(如果它们尚未由前一次对象创建过程初始化),接着是非static 对象。
class prt {
prt(int cc){
System.out.println("prt(" + cc + ")");
}
}
class demo {
prt first = new prt(1);
static prt second = new prt(2);
}
public class StaticVar {
public static void main(String [] args) {
demo d = new demo();
}
}
运行结果:
[img]/upload/attachment/93016/ae8649d6-f6dc-3450-bbe5-8aecab740e31.gif[/img]