Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous code block in anonymous class Java [duplicate]

Possible Duplicate:
What is Double Brace initialization in Java?

While looking at some legacy code I came across something very confusing:

 public class A{
      public A(){ 
          //constructor
      }
      public void foo(){
            //implementation ommitted
      }
 }

 public class B{
      public void bar(){
           A a = new A(){ 
                { foo(); }
           }
      }
 }

After running the code in debug mode I found that the anonymous block { foo() } is called after the constructor A() is called. How is the above functionally different from doing:

 public void bar(){
       A a = new A();
       a.foo();
 }

? I would think they are functionally equivalent, and would think the latter way is the better/cleaner way of writing code.

like image 802
fo_x86 Avatar asked Jan 08 '13 20:01

fo_x86


2 Answers

 { foo(); }

is called instance initializer.

why?

As per java tutorial

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.

like image 88
kosa Avatar answered Oct 13 '22 19:10

kosa


"Instance initializers are a useful alternative to instance variable initializers whenever: (1) initializer code must catch exceptions, or (2) perform fancy calculations that can't be expressed with an instance variable initializer. You could, of course, always write such code in constructors. But in a class that had multiple constructors, you would have to repeat the code in each constructor. With an instance initializer, you can just write the code once, and it will be executed no matter what constructor is used to create the object. Instance initializers are also useful in anonymous inner classes, which can't declare any constructors at all."Source

This was also quoted in this answer.

like image 38
NominSim Avatar answered Oct 13 '22 21:10

NominSim