2

Why does Java accept a brackets only method? What is made for?

{
    // Do something
}

I also noticed that it is executed automatically after the static-block but before the constructor. Although the constructor of the super class is executed before.

Is there a specific reason for this order?

This is the JUnit I made for discovering the execution order:

public class TestClass extends TestSuperClass {

    public TestClass() {
        System.out.println("constructor");
    }

    @Test
    public void test() {
        System.out.println("test");
    }

    {
        System.out.println("brackets");
    }

    static {
        System.out.println("static");
    }
}

public class TestSuperClass {

    public TestSuperClass() {
        System.out.println("super class constructor");
    }

    {
        System.out.println("super class brackets");
    }

    static {
        System.out.println("super class static");
    }
}

As output I get:

super class static
static
super class brackets
super class constructor
brackets
constructor
test
Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
  • *"Is there a specific reason for this order?"* - It is explained in JLS 15.9.4 - http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.9.4 – Stephen C Sep 04 '17 at 14:02

1 Answers1

2

It is the same as static block but just not static. So it will execute in the order that you already found out - after super constructor but before constructor. However, if static-block can be useful regular block not so much. So it is never used, but it is legal. I never saw it used and can not think of any particular purpose, but it is part of valid syntax. If it was not then static block wouldn't be either.

Michael Gantman
  • 7,315
  • 2
  • 19
  • 36
  • I've actually seen it used once : in a very long method creating UI components, it was used to limit scope of local variables. It's the half-baked way of extracting code in another method. A bad practice IMO. – Jeremy Grand Apr 19 '17 at 13:56
  • Sure, I agree Jeremy, bad practice in IMHO as well. Just proves my point that it is never used and when it is - it shouldn't have been – Michael Gantman Apr 19 '17 at 14:06