如何打印对象的默认值?
How to print the default value of an object?
如果t1给出编译错误,t2打印内存地址,t3打印null,
那么你会写什么来获得一个对象的默认值(空)打印。
public class Test {
public Test{
}
public static void main(String[] args) {
Test t1;
Test t2= new Test();
Test t3= null;
System.out.println(t1); //compile error uninitialized
System.out.println(t2); //prints memory address
System.out.println(t3); //prints null
}
}
只有实例或静态变量(在 class 范围内声明)有默认值。局部变量(在方法范围内声明)没有默认值:您需要在使用它们之前初始化这些变量。
所以编译器在拒绝打印 t1
时是正确的(有编译错误):你还没有在方法中的那个点给这个变量赋值,它是一个局部变量, 所以它 没有 有默认值。
只有变量有默认值。一个对象包含所述变量或其他对象也包含变量或其他对象等
这里的变量是方法中的局部变量。来自 Java doc:
The compiler will assign a reasonable default value for fields of the
above types; for local variables, a default value is never assigned.
所以你需要手动初始化它们。
如果t1给出编译错误,t2打印内存地址,t3打印null, 那么你会写什么来获得一个对象的默认值(空)打印。
public class Test {
public Test{
}
public static void main(String[] args) {
Test t1;
Test t2= new Test();
Test t3= null;
System.out.println(t1); //compile error uninitialized
System.out.println(t2); //prints memory address
System.out.println(t3); //prints null
}
}
只有实例或静态变量(在 class 范围内声明)有默认值。局部变量(在方法范围内声明)没有默认值:您需要在使用它们之前初始化这些变量。
所以编译器在拒绝打印 t1
时是正确的(有编译错误):你还没有在方法中的那个点给这个变量赋值,它是一个局部变量, 所以它 没有 有默认值。
只有变量有默认值。一个对象包含所述变量或其他对象也包含变量或其他对象等
这里的变量是方法中的局部变量。来自 Java doc:
The compiler will assign a reasonable default value for fields of the above types; for local variables, a default value is never assigned.
所以你需要手动初始化它们。