Curly curly braces only method

Why does Java only accept a method for parentheses? What's done for?

{
    // Do something
}

      

I also noticed that it is executed automatically after the static-block , but before the constructor. Although the superclass constructor is executed before.

Is there a specific reason for this order?

This is the JUnit I made to detect 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 an output, I get:

super class static
static
super class brackets
super class constructor
brackets
constructor
test

      

+3


source to share


1 answer


This is the same as a static block, but not static. That way, it will execute in the order you've already learned - after the super-constructor, but before the constructor. However, if a static block can be useful a regular block is not much. Therefore, it is never used, but it is legal. I have never seen it used and could not think of any specific purpose, but this is part of the actual syntax. If it wasn't, then the static block wouldn't be there either.



+2


source







All Articles