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.
In a Java program, everything is subordinate to the top line — the line with class in it. To indicate that everything else in the code is subordinate to this class line, you use curly braces. Everything else in the code goes inside these curly braces. \
Braces are used around all statements, even single statements, when they are part of a control structure, such as an if-else or for statement. This makes it easier to add statements without accidentally introducing bugs due to forgetting to add braces.
In programming, curly braces (the { and } characters) are used in a variety of ways. In C/C++, they are used to signify the start and end of a series of statements. In the following expression, everything between the { and } are executed if the variable mouseDOWNinText is true.
Another key element of Java is the code block. A code block is a grouping of two or more statements. This is done by enclosing the statements between opening and closing curly braces. Once a block of code has been created, it becomes a logical unit that can be used any place that a single statement can.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With