java的没括号是什么,在Java中,为什么没有关键字的代码块,只是大括号

博客探讨了Java中未标记代码块的作用,它实际上是一个实例初始化块,类似于构造函数,用于共享多个构造器之间的代码。作者指出,虽然编译器会将初始化块复制到所有构造器中,但个人更倾向于使用命名初始化方法以提高可读性。这种设计决策可能影响代码的构造和性能,尤其是在使用工厂方法时。
摘要由CSDN通过智能技术生成

I'm re-factoring some inherited code, but was stumped by the design decision and can't figure out the proper terms to google this. My predecessor would use blocks like this one:

public class ChildClass extends ParentClass {

{

inheritedVar = "someVal";

}

public ChildClass(){ /* constructor exists */ }

// rest of code

}

What is the point of declaring a block of code with no keyword? It doesn't behave like a static block, I don't believe. Is it an alternative to setting in the constructor? Would this have some effect if a factory was being used (which in this case it's not)? I found a related thread here on this happening in C but the reasoning (scope & variable declaration) didn't seem relevant to Java.

Any thoughts or ideas on the "why" of this would be appreciated. It's easy enough to re-factor this, I'm just curious at this point.

解决方案

It is an initializer block. (Related to static initializer block) See Initializing Instance Members on this page:

It is an alternative to a constructor. You could use it when providing multiple, overloaded constructors as a way to share code.

Personally, however, I find it much clearer to have the constructor call a named initializer method rather than rely on the anonymous code block. Although, the compiler does copy the initializer block to all constructors behind the scenes and you could argue that there is a performance increase similar to inline'ing a method declaration.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值