Anonymous code block in anonymous class Java
Possible Duplicate:
What is Double Brace initialization in Java?
在查看一些遗留代码时,我遇到了一些令人困惑的事情:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public class A{ public A(){ //constructor } public void foo(){ //implementation ommitted } } public class B{ public void bar(){ A a = new A(){ { foo(); } } } } |
在调试模式下运行代码后,我发现在调用构造函数
1 2 3 4 | public void bar(){ A a = new A(); a.foo(); } |
? 我认为它们在功能上是等价的,并且认为后一种方式是更好/更清晰的编写代码的方式。
1 | { foo(); } |
被称为实例初始化器。
why?
按照java教程
Java编译器将初始化程序块复制到每个构造函数中。 因此,该方法可用于在多个构造函数之间共享代码块。
"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
这个答案也引用了这一点。
除非访问对象的运行时类(通过调用