I am still on the learning curve in Java. To understand a little more initializer blocks, I created a small test class:
public class Script { { Gadgets.log("anonymous 1"); } public Script() { Gadgets.log("constructor"); } { Gadgets.log("anonymous 2"); } }
When I create an instance, I get this log:
Script: anonymous 1 Script: anonymous 2 Script: constructor
This tells me that both initialization blocks are executed before the constructor in the order they appear in the source code (just like static initializers). I want to know if I have a little more control over this behavior? As the Java Documentation says ( source ):
Initializer blocks for instance variables look like static initializers, but without a static keyword:
{ // whatever code is needed for initialization goes here }
The Java compiler copies initialization blocks to each constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
So what does it mean "copy initializer blocks to each constructor"? In my journal, it looks like they are copied at the beginning of each constructor. Is it correct?
Sharing such blocks between multiple constructors will also make sense if they are copied to the END of each constructor (as I expected from anonymous 2). Is there a way to control these blocks a little more, or is my only option a βclassicβ way to write a named method that is called in each constructor if I want to perform common tasks at the end of each constructor?
java
Grisgram
source share