关于变量x3,哪个构造函数初始化它?我似乎无法弄清楚。它会是类 X 的无参数构造函数吗?或者也许是对象类的默认构造函数?
class X {
int x1, x2, x3;
}
最佳答案
x3
是一个实例变量,它的默认值为 0(对于 int)。来自 Java 文档:
It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type.
Relying on such default values, however, is generally considered bad programming style.
如果它是局部变量(例如您在方法中创建的变量),则必须对其进行初始化。所以我会说,class X
的默认构造函数初始化了x3
,或者你可以说,默认情况下它会被初始化为0。
关于java - 通过构造函数初始化变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35209962/