java中声明变量不初始化会占用内存吗,未初始化的原始实例变量是否使用内存?...

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;?

Details:

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.

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

For class members :

int i;

is the same as :

int i = 0;

Here's what the JLS says about instance variables :

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值