1
0

More than 1 year has passed since last update.

var

Posted at

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.
1
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
1
0