「Java」匿名クラスでメソッドのオーバーライドを利用する方法

2020年12月18日

構文
new クラス名() {
@Override
public 戻り型  関数名
}
サンプルコード

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() {
@Override
public void printMsg() {
System.out.println("method override: test123456");
}
}.printMsg();
// クラスのオブジェクト作成
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);
}
}
package com.example.demo; public class StudytokumDemo { public static void main(String[] args) { // 匿名クラス new User() { @Override public void printMsg() { System.out.println("method override: test123456"); } }.printMsg(); // クラスのオブジェクト作成 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); } }
package com.example.demo;

public class StudytokumDemo {
      public static void main(String[] args) {
            // 匿名クラス
            new User() {
                  @Override
                  public void printMsg() {
                        System.out.println("method override: test123456");
                  }
            }.printMsg();
            // クラスのオブジェクト作成
            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 override: test123456
study java in arkgame.com

Java

Posted by arkgame