java实例的字段,java静态实例字段和构造函数

In a Java class with static instance fields, is the constructor called every time the fields are accessed, or only on the first access? I initialize the static fields in the constructor, and was wondering if this would cause a slow down because the fields are initialized on every access.

解决方案

I initialize the static fields in the constructor,

Don't. Never initialize static fields inside a constructor. static fields are not something associated with any instance of a class. It is bound to class. There is only single copy of that variable, that is accessed accross all the instances. So, if you are initializing it in constructor, then every time you create an instance, that field will be re-initialized for every other instance.

You should use static initializer block to initialize your static fields, or just initialize them at the place of declaration.

class Demo {

private static int x; // Either initialize it here.

static { // Or use static initializer block

x = 10;

}

}

with static instance fields, is the constructor called every time the fields are accessed,

No. , static fields are accessed on class. They are loaded and initialized when the class is loaded. And then you can modify it later on, on class name, in which case, the change will be effected for all the instances. So, the constructor will not be invoked, whenever you access static field.

In fact, even when you access instance field, constructor is not invoked every time. Constructor is used to initialize the state of the newly created instance once. And for further access and modification of that field, constructor won't be invoked.

So, a constructor has precisely no role to play whenever you want to access any fields of your class.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值