0
0

Java gold 例題 匿名クラス

Last updated at Posted at 2024-08-07

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 と表示される。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0