gpt4 book ai didi

java - 未初始化的原始实例变量是否使用内存?

转载 作者:IT老高 更新时间:2023-10-28 20:41:58 24 4
gpt4 key购买 nike

在Java中,声明一个类级别的实例变量而不初始化它会消耗内存吗?
例如:如果我不使用 i = 5; 对其进行初始化,int i; 是否会使用任何内存?

详情:

我有一个巨大的父类(super class),它扩展了许多不同的(差异不足以拥有自己的父类(super class))子类。一些子类不使用父类(super class)声明的每一个原语。我可以简单地将这些原语保持为未初始化,并且只在必要的子类中初始化它们以节省内存吗?

最佳答案

类中定义的所有成员都有默认值,即使您没有显式初始化它们,所以它们确实使用内存。

例如,每个int都会默认初始化为0,占用4字节。

对于类(class)成员:

int i;

等同于:

int i = 0;

这里是 JLS说的是实例变量:

If a class T has a field a that is an instance variable, then a new instance variable a is created and initialized to a default value (§4.12.5) as part of each newly created object of class T or of any class that is a subclass of T (§8.1.4). The instance variable effectively ceases to exist when the object of which it is a field is no longer referenced, after any necessary finalization of the object (§12.6) has been completed.

关于java - 未初始化的原始实例变量是否使用内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26585220/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com