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

説明
super()で親クラスのメソッドを子クラスで継承します
1.親クラスの定義

package com.arkgame.study.java;

// class definition
public class EmpParentDemo {

      String empId;
      Integer age;

      // parent constructor
      public EmpParentDemo(String empId, Integer age) {
            this.empId = empId;
            this.age = age;
      }

      // parent method parentRes definition
      public String parentRes() {
            String target = "Parent method is called AA001";
            return target;
      }

}

2.子クラスの定義

package com.arkgame.study.java;

// child class extends
public class EmpChildDemo extends EmpParentDemo {

      String depId;

      // child class constructor
      public EmpChildDemo(String empId, Integer age, String depId) {
            super(empId, age);
            this.depId = depId;
      }
    //super.親クラスのメソット
      public String childRes() {
            return super.parentRes();
      }

}

3.実行確認(main)

package com.arkgame.study.java;

public class EmpSuperMethod {

      public static void main(String[] args) {

            //child object statement
            EmpChildDemo eCh = new EmpChildDemo("A001", 32, "AB");
            //child class method is called
            String result = eCh.childRes();
            System.out.println(result);

      }

}

4.実行結果
Parent method is called AA001

Java

Posted by arkgame