「Java」superで親クラスの関数とメンバ変数を利用するサンプル
書式
super.親クラスのメンバ変数
super.親クラスの変数名
使用例
package com.arkgame.study;
//親クラスの定義
class ParentA {
int age = 12;
public void printMsg() {
this.age = 34;
System.out.println("親クラス--メンバ変数age: " + age);
}
}
//子クラスの定義
class ChildA extends ParentA {
public void printMsg() {
//superで親クラスのメンバーを書き換える
super.age = 56;
System.out.println("子クラス--メンバ変数age: " + age);
}
public void display() {
//子クラス
printMsg();
//スーパークラスのメソッドを呼ぶ
super.printMsg();
}
}
//動作確認クラス
public class SuperFormDemo {
public static void main(String[] args) {
ParentA pa = new ParentA();
System.out.println("親クラスのメンバー変数: " + pa.age);
//子クラスのオブジェクトの作成
ChildA cft = new ChildA();
cft.display();
}
}
package com.arkgame.study;
//親クラスの定義
class ParentA {
int age = 12;
public void printMsg() {
this.age = 34;
System.out.println("親クラス--メンバ変数age: " + age);
}
}
//子クラスの定義
class ChildA extends ParentA {
public void printMsg() {
//superで親クラスのメンバーを書き換える
super.age = 56;
System.out.println("子クラス--メンバ変数age: " + age);
}
public void display() {
//子クラス
printMsg();
//スーパークラスのメソッドを呼ぶ
super.printMsg();
}
}
//動作確認クラス
public class SuperFormDemo {
public static void main(String[] args) {
ParentA pa = new ParentA();
System.out.println("親クラスのメンバー変数: " + pa.age);
//子クラスのオブジェクトの作成
ChildA cft = new ChildA();
cft.display();
}
}
package com.arkgame.study; //親クラスの定義 class ParentA { int age = 12; public void printMsg() { this.age = 34; System.out.println("親クラス--メンバ変数age: " + age); } } //子クラスの定義 class ChildA extends ParentA { public void printMsg() { //superで親クラスのメンバーを書き換える super.age = 56; System.out.println("子クラス--メンバ変数age: " + age); } public void display() { //子クラス printMsg(); //スーパークラスのメソッドを呼ぶ super.printMsg(); } } //動作確認クラス public class SuperFormDemo { public static void main(String[] args) { ParentA pa = new ParentA(); System.out.println("親クラスのメンバー変数: " + pa.age); //子クラスのオブジェクトの作成 ChildA cft = new ChildA(); cft.display(); } }
実行結果
親クラスのメンバー変数: 12
子クラス–メンバ変数age: 56
親クラス–メンバ変数age: 34