java 默认构造函数不初始化类的实例成员?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38604422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Default constructor does not initialize the instance members of the class?
提问by SERich
I encountered a question that asks "Which of the following are true about the "default" constructor?"
我遇到了一个问题,询问“关于“默认”构造函数,以下哪些是正确的?
and an option "It initializes the instance members of the class." was incorrect choice.
和一个选项“它初始化类的实例成员。” 是错误的选择。
Now my understanding was that if we have a code such as
现在我的理解是,如果我们有一个代码,例如
Class Test {
String name;
}
then the compiler creates default constructor that looks like
然后编译器创建默认构造函数,看起来像
Class Test {
String name;
Test(){
super();
name = null;
}
}
Isn't the default constructor initializing the instance member name=null ?
默认构造函数不是初始化实例成员 name=null 吗?
回答by smac89
The class constructor is not the one doing the initialization, the JVM does this.
类构造函数不是进行初始化的,JVM 会这样做。
After memory for the object is created, the members of the object are default initialized to some predictable value, which becomes their default value. This is all done beforethe constructor is called!
创建对象的内存后,对象的成员默认初始化为某个可预测的值,该值成为它们的默认值。这一切都是在调用构造函数之前完成的!
According to the specification
根据规范
- Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10.2):
- For type byte, the default value is zero, that is, the value of
(byte)0
.- For type short, the default value is zero, that is, the value of
(short)0
.- For type int, the default value is zero, that is,
0
.- For type long, the default value is zero, that is,
0L
.- For type float, the default value is positive zero, that is,
0.0f
.- For type double, the default value is positive zero, that is,
0.0d
.- For type char, the default value is the null character, that is,
'\u0000'
.- For type boolean, the default value is
false
.- For all reference types (§4.3), the default value is
null
.
Your assumption is close but the fact is, before the constructor parameters are even evaluated, before it can even assign a value to each of the fields - those fields already hold their default values, and this is done by the JVM.
您的假设很接近,但事实是,甚至在评估构造函数参数之前,甚至在它甚至可以为每个字段分配值之前 - 这些字段已经保存了它们的默认值,这是由 JVM 完成的。
Read subsection §15.9.4to understand how the initialization process is carried out
阅读第15.9.4 节以了解初始化过程是如何进行的
回答by Cheng Chen
In Java fields are initialized beforethe constructor. This can be easily proved by the following code:
在 Java 中,字段在构造函数之前被初始化。这可以通过以下代码轻松证明:
public class MyClass {
int myField = initMyField();
MyClass(){
System.out.println("ctor");
}
static int initMyField() {
System.out.println("init field");
return 1;
}
}
output
输出
init field
ctor
You can also check the de-compiled code.
您还可以检查反编译的代码。
回答by Andrew Tobilko
Isn't the default constructor initializing the instance member
name = null
?
默认构造函数不是初始化实例成员
name = null
吗?
No, constructors get called afterall instance variables are initialized by the default values: 0
or the equivalent value for primitive numerical types, false
for the boolean
type, null
for reference types.
不,构造函数被调用后,所有的实例变量由缺省值初始化:0
或等值原始数值类型,false
对于boolean
类型null
为引用类型。
回答by RCInd
It does. Although the question is based more on usage.
确实如此。虽然问题更多地基于使用。
public class Main {
String x;
Main() {
x = "Init";
}
@Override
public String toString() {
return x;
}
public static void main(String[] args) {
System.out.println(new Main());
}
}
Ouput:
输出:
Init
回答by user3437460
No, it is not the default constructor which initialize the instance variables for you. Each type has a default value. The moment you created the object, the default value is used.
不,它不是为您初始化实例变量的默认构造函数。每种类型都有一个默认值。创建对象的那一刻,将使用默认值。
So if you do not explicitly initialize the instance variables, they will be still using the default values defined for them implicitly.
因此,如果您不显式初始化实例变量,它们仍将使用为它们隐式定义的默认值。
i.e. 0 for int, null for reference type.. etc
即 0 表示 int,null 表示引用类型......等
However, it is worth noting that we should not take it for granted that a default value is given, and choose not to initialize the variables.
但是,值得注意的是,我们不应想当然地认为给出了默认值,而选择不初始化变量。
You may try defining an empty constructor which override the default constructor with empty implementation. You will realize all instance variables will still be initialized.
您可以尝试定义一个空构造函数,该构造函数覆盖具有空实现的默认构造函数。您将意识到所有实例变量仍将被初始化。
回答by mc.Ambugo
Default constructor provides the default values to the object (s) and is normally created by the compiler when no constructor is explicitly defined. e.g.
默认构造函数为对象提供默认值,通常在没有显式定义构造函数时由编译器创建。例如
class DefaultTest{
int id;
String name;
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
DefaultTest s1=new DefaultTest();
DefaultTest s2=new DefaultTest();
s1.display();
s2.display();
}
}
NB: There being no constructor defined the compiler will generate a default constructor that will assign 0 null values to the two objects.
注意:没有定义构造函数,编译器将生成一个默认构造函数,该构造函数将为两个对象分配 0 空值。
回答by Rajdeep Sarkar
Whenever we are executing a java class, first Static Control Flow will be executed. In the Static Control Flow if we are creating an object then the following steps will be executed(in the mentioned order) as a part of Inatance Control Flow:
每当我们执行一个 java 类时,首先会执行静态控制流。在静态控制流中,如果我们正在创建一个对象,那么以下步骤将作为 Inatance 控制流的一部分执行(按上述顺序):
- Identification of instance members(instance variable and instance blocks) from top to bottom.
- Execution of instance variable assignments and instance blocks.
- Execution of constructor.
- 从上到下识别实例成员(实例变量和实例块)。
- 执行实例变量分配和实例块。
- 构造函数的执行。
So, in your above code the instance variable "name" is already assigned to null(default value for reference types) even before the constuctor is executed.
因此,在您上面的代码中,即使在执行构造函数之前,实例变量“名称”也已分配给 null(引用类型的默认值)。