JAVA构造函数声明正确表达,java – 我应该实例化声明或构造函数中的实例变量吗?...

博客讨论了Java中实例变量初始化的方式,指出初始化通常由编译器置于构造函数中。第一种变体更易读,但不适用于异常处理。初始化块用于延迟初始化,特别是在操作昂贵时。建议避免在类内直接使用`new`关键字,推荐采用依赖注入来管理依赖。
摘要由CSDN通过智能技术生成

>没有区别 – 实例变量初始化实际上是由编译器放在构造函数中。

>第一个变体更易读。

>您不能使用第一个变量进行异常处理。

>还有一个初始化块,它也是由编译器放在构造函数中:

{

a = new A();

}

Field declarations, however, are not part of any method, so they cannot be executed as statements are. Instead, the Java compiler generates instance-field initialization code automatically and puts it in the constructor or constructors for the class. The initialization code is inserted into a constructor in the order it appears in the source code, which means that a field initializer can use the initial values of fields declared before it.

此外,您可能需要延迟初始化字段。在初始化字段是昂贵的操作的情况下,您可以在需要时立即初始化它:

ExpensiveObject o;

public ExpensiveObject getExpensiveObject() {

if (o == null) {

o = new ExpensiveObject();

}

return o;

}

最终(如Bill所指出的),为了依赖管理,最好避免在类中的任何地方使用新运算符。相反,使用Dependency Injection是更好的 – 即让别人(另一个类/框架)实例化和注入类中的依赖。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值