开发者

On static and non-static initializing blocks in Java

I originally thought that static blocks were for static variables but the compiler allows both A and B to compile and run, what gives?

A

   private static final Map<String,String> m = new HashMap<String,String>();

        {
            m.put("why", "does");
            m.put("this","wor开发者_高级运维k");
        }

B

 private static final Map<String,String> m = new HashMap<String,String>();

        static{
               m.put("why", "does");
               m.put("this","work");
             }

Running System.out.println(Main.m.toString()); for A prints

{}

but running the same for B prints out in Yoda-speak

{this=work, why=does}


The non static block is executed when an "instance" of the class is created.

Thus

System.out.println(Main.m.toString());

prints nothing because you haven't created an instance.

Try creating an instance first

 Main main = new Main();

and you'll see the same message as B

As you know class variables (declared using static) are in scope when using instance blocks.

See also:

Anonymous Code Blocks In Java


In A, you have an instance initializer. It will be executed each time you construct a new instance of A.

If multiple threads are constructing A instances, this code would break. And even in a single thread, you normally don't want a single instance to modify state that is shared by every instance. But if you did, this is one way to achieve it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜