[Java]this、extendsとsuperのサンプル

2021年4月9日

書式
super.親クラスのメソッド
親クラスの定義

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.serializ.demo;
//スーパークラス
public class BaseParent {
protected String userid = null;
// メソッドshow
public void show() {
this.userid = "user1009";
System.out.println("ユーザID:" + userid);
}
}
package com.arkgame.serializ.demo; //スーパークラス public class BaseParent { protected String userid = null; // メソッドshow public void show() { this.userid = "user1009"; System.out.println("ユーザID:" + userid); } }
package com.arkgame.serializ.demo;

//スーパークラス
public class BaseParent {

      protected String userid = null;

      // メソッドshow
      public void show() {
            this.userid = "user1009";
            System.out.println("ユーザID:" + userid);
      }
}

子クラスの定義

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.serializ.demo;
//子クラス
public class BaseChild extends BaseParent {
protected int age = 32;
// メソッドshow
public void show() {
super.show();
this.age = 36;
System.out.println("年齢:" + age);
}
//動作確認
public static void main(String[] args) {
BaseChild bChild = new BaseChild();
bChild.show();
}
}
package com.arkgame.serializ.demo; //子クラス public class BaseChild extends BaseParent { protected int age = 32; // メソッドshow public void show() { super.show(); this.age = 36; System.out.println("年齢:" + age); } //動作確認 public static void main(String[] args) { BaseChild bChild = new BaseChild(); bChild.show(); } }
package com.arkgame.serializ.demo;

//子クラス
public class BaseChild extends BaseParent {

      protected int age = 32;

      // メソッドshow
      public void show() {
            super.show();
            this.age = 36;
            System.out.println("年齢:" + age);
      }

//動作確認
      public static void main(String[] args) {
            BaseChild bChild = new BaseChild();
            bChild.show();
      }

}

実行結果
ユーザID:user1009
年齢:36

Java

Posted by arkgame