「Java」匿名クラスにメソットを追加するサンプル
構文
new 匿名クラス(){
public 戻り型 新関数名
}
サンプルコード
package com.example.demo;
public class StudytokumDemo {
public static void main(String[] args) {
// 匿名クラス
new User() {
//メソッドを追加する
public void printMsg2() {
System.out.println("method add test 1234");
}
}.printMsg2();
// クラスのオブジェクト作成
User user = new User();
user.printMsg();
}
}
//クラスの定義
class User {
String strA = "study java ";
String strB = "in arkgame.com";
public void printMsg() {
String res = strA.concat(strB);
System.out.println(res);
}
}
実行結果
method add test 1234
study java in arkgame.com