Java 尽力保证:所有变量在使用前都能得到恰当的初始化。对于方法的局部变量,必须在使用时为变量赋一个默认值,否则编译器会报错
对于类的数据成员(即字段) 是基本类型,如果定义是没有初值,编译器也会给一个初始值, 如果是在类里定义一个对象引用时,如果不将其初始化,此引就会获得一只特殊值null
class InitialValues{
// 只定义字段不赋值
boolean t;
char c;
byte b;
short s;
int i;
long l;
float f;
double d;
InitialValues reference;
void printInitialValues(){
System.out.println("Data type Initial value");
System.out.println("boolean " + t); // boolean 初始值false
System.out.println("char " + c); // char 初值为0,所以为空
System.out.println("byte " + b); // byte 初值为0
System.out.println("short " + s); // short 初值为0
System.out.println("int " + i); // int 初值为0
System.out.println("long " + l); // long 初值为0
System.out.println("double " + d); // double 初值为0.0
System.out.println("InitialValues " + reference); // 引用类型reference 初值为null
}
public static void main(String[] args) {
InitialValues initialValues = new InitialValues();
initialValues.printInitialValues();
/**
* 可以使用这种写法
* new InitialValues.printInitialValues();
*/
}
}
指定初始化 就是在定义类成员变量的地方为其赋值
class Depth{}
class InitialValues{
// 定义字段并赋值
boolean t = true;
char c = 'x';
byte b = 47;
short s = 0xff;
int i = 999;
long l = 1;
float f = 3.14f;
double d = 3.14159;
InitialValues reference;
Depth dep = new Depth(); // 为引用类型赋值,如果没有指定初始值就尝试使用,会出现运行时错误
}
通过调用某个方法来提供初值 ,并且这个方法也可以带有参数,但这些参数必须是已经被初始化了的
class MethodInit{
int i = f(); // 通过调用某个方法来提供初值
int j = g(i); // 方法可以带已经初始化了的参数
int f(){
return 11;
}
int g(int n){
return n * 10;
}
}
但是这样写会报错:
class MethodInit{
// int j = g(i); // 会报错
int i = f(); // 通过调用某个方法来提供初值
int f(){
return 11;
}
int g(int n){
return n * 10;
}
}
上述程序的正确性取决于初始化的顺序,而与其编译方式无关。所以,编译器对这种“向前引用”报错