public class AnonymousClassTest {
public static void main(String[] args) {
Sample sample = new Sample() {
{
super.print();
}
Sample() {
System.out.println("B");
}
@Override
void print() {
System.out.println("anonymous");
}
};
sample.print();
}
}
class Sample {
Sample() {
System.out.println("Sample");
}
void print() {
System.out.println("print");
}
}
コードを実行するとどうなりますか?
1.Sampleと表示される
2.printと表示される
3.Bと表示される
4.print B anonymous と表示される
5.Sample print anonymous と表示される
6.コンパイルエラー
解答
6匿名クラスの問題。匿名クラスではコンストラクターを定義することができない。
そのため、単なるメソッドとして扱われるが、戻り値もないためコンパイルエラー。
匿名クラス内のSample(){ }部分を消すと、Sample print anonymous と表示される。