「Java」superで親クラスのメソッドを呼び出すサンプル

2021年7月21日

書式
super.スーパークラスのメソッド名
使用例
1.スーパークラス

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.info;
//親クラス
public class ParentA {
public void funcA() {
System.out.println("super class message 123456");
}
}
package com.arkgame.info; //親クラス public class ParentA { public void funcA() { System.out.println("super class message 123456"); } }
package com.arkgame.info;

//親クラス
public class ParentA {

      public void funcA() {
            System.out.println("super class message 123456");
      }
}

2.子クラス

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.info;
//子クラスの定義
public class ChildA extends ParentA {
public static void main(String[] args) {
// 子クラスのオブジェクトを生成
ChildA obj = new ChildA();
// 自分のメソッドを呼び出す
obj.funcAA();
}
public void funcAA() {
System.out.println("child class is called");
// 親クラスのメソッドを呼び出す
super.funcA();
}
}
package com.arkgame.info; //子クラスの定義 public class ChildA extends ParentA { public static void main(String[] args) { // 子クラスのオブジェクトを生成 ChildA obj = new ChildA(); // 自分のメソッドを呼び出す obj.funcAA(); } public void funcAA() { System.out.println("child class is called"); // 親クラスのメソッドを呼び出す super.funcA(); } }
package com.arkgame.info;

//子クラスの定義
public class ChildA extends ParentA {

      public static void main(String[] args) {
            // 子クラスのオブジェクトを生成
            ChildA obj = new ChildA();
            // 自分のメソッドを呼び出す
            obj.funcAA();
      }

      public void funcAA() {

            System.out.println("child class is called");

            // 親クラスのメソッドを呼び出す
            super.funcA();
      }

}

3.実行結果

child class is called
super class message 123456

Java

Posted by arkgame