Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-Static initializer blocks - do I have a bit more control?

Tags:

java

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?

like image 452
Grisgram Avatar asked Apr 07 '16 00:04

Grisgram


1 Answers

A constructor executes in the following order:

  1. super() call, implicit or explicit.
  2. Variable initializers and initializer blocks, in the order they appear in the source code.
  3. Remainder of the constructor.

This is specified in the JLS and cannot be altered.

If a this() call is present it replaces (1) and (2).

like image 172
user207421 Avatar answered Nov 03 '22 14:11

user207421