varは型推論
Objectに存在しないtestメソッドを定義することで
Objectではない別のクラスを推論して宣言する
public class Outer {
public static void main(String[] args) {
var obj = new Object() {
public void test() {
System.out.println("i am test method");
}
};
obj.test();
}
}
i am test method
Objectで宣言するとエラー。
public class Outer {
public static void main(String[] args) {
Object obj = new Object() {
public void test() {
System.out.println("i am test method");
}
};
obj.test(); //error
}
}
Exception in thread "main" java.lang.RuntimeException: Uncompilable code - シンボルを見つけられません
シンボル: メソッド test()
場所: タイプjava.lang.Objectの変数 obj
at com.mycompany.mavenproject1.Outer.main(Outer.java:1)
Command execution failed.