Tom*_*ato 2 java memory memory-management
我知道只要字段存在就会粘贴到对象上,因此它们会分配一些内存,但是如果我不初始化某些字段而不使用它们会怎么样?例如:
public class TEST {
public static void main(String[] args) {
Foo C = new Foo(5, 7);
Foo D = new Foo(5);
...
}
public class Foo{
private int A;
private float B;
public Foo (int A, float B){
this.A = A;
this.B = B;
}
public Foo (int A){
this.A = A;
}
...
}
Run Code Online (Sandbox Code Playgroud)
会C消耗更多的内存D吗?
Java中的字段始终初始化.基元初始化为0或false,并且引用(和数组)初始化为null.
此外,一旦声明了一个字段,该字段将始终占用每个实例中的相同空间.引用只占用与指针一样多的空间,但引用的对象可能需要额外的内存.