以下变量声明之间有区别吗?
Class A {
private int a;
A(){
a= 2;
}
}
VS
Class A {
private int a = 2;
A(){
}
}
垃圾收集的工作方式会有什么不同吗?
以下变量声明之间有区别吗?
Class A {
private int a;
A(){
a= 2;
}
}
VS
Class A {
private int a = 2;
A(){
}
}
垃圾收集的工作方式会有什么不同吗?
No there is no difference because the java compiler initialize "private int a = 2" inside the constructor internally. You can use java decompiler to confirm my above statement. So for both GC will work same.
您的两个初始化的行为没有区别。在第一个示例中,a = 2
将在调用构造函数代码之前发生。如果你做了a
决赛:
private final int a; //first example
private final int a = 2; //second example
然后你会看到你可以在构造函数中做的事情之间的区别:
A(){ //The blank final field a may not have been initialized for first example
}
A(){
a = 2; //The final field Apple.a cannot be assigned for second example
}
In both cases you are declaring int a
as a member variable of the class. Whenever the class is instantiated, space will be set aside on the heap for that integer. However, the garbage collector only cares about whether or not there are any references to the containing object that has been instantiated. Regardless of what you do with the member variables, the object will stay in memory if there is a reference to it, after which point it's eligible for garbage collection.
However, perhaps you believe there should be a difference? Why is that?