9

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.

Community
  • 1
  • 1
fo_x86
  • 2,583
  • 1
  • 30
  • 41
  • 1
    See [initialization of variable - Oracle Tutorial](http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html) – Rohit Jain Jan 08 '13 at 20:47
  • 1
    this might be helpful - http://stackoverflow.com/questions/1355810/how-is-an-instance-initializer-different-from-a-constructor – Avinash T. Jan 08 '13 at 20:48
  • ty, I found that link after I discovered that the "anonymous block" is actually called "instance initializer". – fo_x86 Jan 08 '13 at 20:52

3 Answers3

8
 { 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.

kosa
  • 65,990
  • 13
  • 130
  • 167
4

"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.

Community
  • 1
  • 1
NominSim
  • 8,447
  • 3
  • 28
  • 38
2

Unless the runtime class of the object is accessed (by means of calling getClass()) and needs to be different from A for some reason (for instance because it serves as super type token), there is indeed no difference, and simply invoking foo() after construction would indeed be the more common idiom.

meriton
  • 68,356
  • 14
  • 108
  • 175