無名クラスのコンストラクタ代わりに instance initializer を使う
import java.util.*; public class A { public static void main(String[] args) { Set<Integer> s = new HashSet<Integer>() { { // instance initializer. System.out.println("constructed."); super.add(0); } @Override public boolean add(Integer x) { System.out.println("added " + x); return super.add(x); } }; s.add(1); s.add(11); System.out.println(s); } }
インスタンスフィールドの初期化をやりたいときに。
ただし、 super(...) は呼べない。
http://www.jguru.com/faq/view.jsp?EID=17355
コメント
Note that an instance initializer is only called once for a class.
は間違いっぽい。
すべてのコンストラクタの先頭にコピーされると思えばいい