简体   繁体   中英

What is the purpose of unnamed code blocks in Java?

In my Java class, I have statements in {} without any names/references associated with it and it appear to get executed before constructor is run. What is the purpose of it? Is it possible to call it like calling a method by associating a variable/reference to it? If not, can I change the order in which it is triggered?

package com.core.java;

public class App {

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

    static { System.out.print("static block, "); }      
    App() { System.out.print("constructor, "); }    
    { System.out.print("what_is_this? "); }

}

I have seen similar construct in Ruby where it can be associated with a reference and be called at will. For instance

v = -> { puts "A Code Block" }
v.call #=> prints -> A Code Block

If you want to have a quick read on these constructs and what they may be used for, see

http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

The comparison to Ruby is somewhat flawed, as this is only a syntactic similarity between Java and Ruby - in Ruby, the "{}" means something completely different to what Java uses this syntax for. The "-> {}" in Ruby is an expression returning a lambda, which is a callable object.

What is an initialization block?

Also helps explaining the case with some nice code examples.

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