在Java中,为什么没有关键字的代码块,只是大括号 [英] In Java, why have a code block with no keywords, just curly brackets
问题描述
public class ChildClass extends ParentClass {
{
inheritedVar = someVal;
}
public ChildClass(){/ *构造函数存在* /}
//其余代码
}
声明一个没有关键字的代码块是什么意思?它不像一个静态块,我不相信。它是替代设置在构造函数吗?如果工厂被使用(在这种情况下不是),这会有一些效果吗?我在这里发生在C 但推理(范围和变量声明)似乎与Java无关。
任何关于为什么的想法或想法将不胜感激。这很简单,可以重新考虑这一点,我只是在这一点好奇。
这是一个初始化程序块。 (与静态初始化程序块相关)请参阅在此页面上初始化实例成员:
http://download.oracle.com/javase/tutorial/java/javaOO/initial.html
它是构造函数的替代方法。当您提供多个重载的构造函数作为共享代码的方法时,您可以使用它。
然而,我个人觉得,让构造函数调用一个名为initializer的方法而不是依赖于匿名代码块。尽管编译器会将初始化程序块复制到幕后的所有构造函数,您可以认为性能提升类似于内联方法声明。
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:
http://download.oracle.com/javase/tutorial/java/javaOO/initial.html
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.
这篇关于在Java中,为什么没有关键字的代码块,只是大括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!