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.
{ 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.
"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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With