简体   繁体   中英

Java coding conventions - what are these curly braces for?

I'm new to JAVA and I've run into the following code snippet.

My question is about the curly braces that surrounds the 2 setter calls.

I can't find anything in the coding conventions http://www.oracle.com/technetwork/java/codeconventions-150003.pdf that explains this code snippet.

Other than to scope the setter calls (but I can't understand the need for that), I can't think of any reason for the curly braces, can someone please explain the purpose of the curly braces? (sorry I didn't have any luck looking for previous questions on this)

Foobar foobar = FoobarManager.getFoobar();
{
    foobar.setName("MyFoo");
    foobar.setTimestamp(timestamp);
}

This is an java initializer block and it is going to work after the super call of your constructor, you can execute the next code

public class Test {
    public Test() {
        super();
        System.out.println("Hello");
    }

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

    public static void main(String[] args) {
        new Test();
    }
}

If you check the output, the result is :

Bye
Hello

This is because fist is going to be executed the super call, after this is going to be executed the initializer block and after this the next lines of your constructor.

It is helpful if you have many constructors and you want to execute some lines of code independently of which constructor was executed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM