「Java」匿名クラスを使うサンプル
説明
new クラス名(){}.関数名()
サンプルコード
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