「Java」匿名クラスを使うサンプル

説明
new クラス名(){}.関数名()
サンプルコード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.example.demo;
public class StudytokumDemo {
public static void main(String[] args) {
// 匿名クラス
new User() {
}.printMsg();
// クラスのオブジェクト作成
User user = new User();
user.printMsg();
}
}
//クラスの定義
class User {
String strA = "welcome study in ";
String strB = "arkgame.com";
public void printMsg() {
String res = strA.concat(strB);
System.out.println("実行結果:" + res);
}
}
package com.example.demo; public class StudytokumDemo { public static void main(String[] args) { // 匿名クラス new User() { }.printMsg(); // クラスのオブジェクト作成 User user = new User(); user.printMsg(); } } //クラスの定義 class User { String strA = "welcome study in "; String strB = "arkgame.com"; public void printMsg() { String res = strA.concat(strB); System.out.println("実行結果:" + res); } }
package com.example.demo;

public class StudytokumDemo {
      public static void main(String[] args) {
            // 匿名クラス
            new User() {
            }.printMsg();

            // クラスのオブジェクト作成
            User user = new User();
            user.printMsg();
      }

}

//クラスの定義
class User {
      String strA = "welcome study in ";
      String strB = "arkgame.com";

      public void printMsg() {
            String res = strA.concat(strB);
            System.out.println("実行結果:" + res);
      }
}

実行結果
welcome study in arkgame.com
welcome study in arkgame.com

Java

Posted by arkgame