I am still on a learning curve in Java. To understand a bit more of 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, both initializer blocks run BEFORE the constructor, in the order they appear in the source code (same as static initializers). What I want to know is: Do I have a little more control over this behavior? Because Java Documentation says (source):
Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:
{
// whatever code is needed for initialization goes here
}
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
So what exactly does "copies initializer blocks into every constructor" mean? According to my log, it seems, they are copied at the beginning of each constructor. Is this right?
Sharing such blocks between multiple constructors would also make perfectly sense, if they were copied to the END of each constructor (that's what I expected in my anonymous 2). Is there a way to control those blocks a bit more or is my only option the "classic" way of writing a named method that gets called in every constructor if I want to do common tasks at the end of each constructor?
A constructor executes in the following order:
super()
call, implicit or explicit.This is specified in the JLS and cannot be altered.
If a this()
call is present it replaces (1) and (2).
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