未初始化的原始实例变量是否使用内存? [英] Do uninitialized primitive instance variables use memory?

查看:680
本文介绍了未初始化的原始实例变量是否使用内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,在没有初始化的情况下声明类级实例变量会花费内存吗?

例如: int i; 使用任何内存,如果我没有用 i = 5; 初始化它?

In Java, does it cost memory to declare a class level instance variable without initializing it?
For example: Does int i; use any memory if I don't initialize it with i = 5;?

详细信息:

我有一个巨大的超级类,许多不同的(不同的,有自己的超级类)子类扩展。有些子类不使用超类声明的每个原语。我可以简单地将这些原语保留为未初始化,并仅在必要的子类中初始化它们以节省内存吗?

I have a huge super-class that many different (not different enough to have their own super classes) sub-classes extend. Some sub-classes don't use every single primitive declared by the super-class. Can I simply keep such primitives as uninitialized and only initialize them in necessary sub-classes to save memory?

推荐答案

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

All members defined in your classes have default values, even if you don't initialize them explicitly, so they do use memory.

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

For example, every int will be initialized by default to 0, and will occupy 4 bytes.

对于班级成员:

int i;

与以下内容相同:

int i = 0;

以下是JLS 说实例变量:


如果类T的字段a是实例变量,则创建新的实例变量a并将其初始化为默认值 (§4.12.5)作为每个新创建的T类对象或任何类的对象的一部分是T(第8.1.4节)的子类。在完成对象(第12.6节)的任何必要的最终化之后,当实例变量不再被引用时,实例变量实际上不再存在。

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.

这篇关于未初始化的原始实例变量是否使用内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆