「Java入門」親子クラスの暗黙的な型の変換のサンプル
書式
親クラス オブジェクト名A = 子クラスのオブジェクト名B
使用例
package com.arkgame.study;
// 親クラス
class ParentAA {
public String testA() {
return "Parent class AAA";
}
}
// 子クラス
class ParentBB extends ParentAA {
public String testB() {
return "Child Class BBB";
}
}
public class ParentObjUse {
public static void main(String[] args) {
// 子クラスのオブジェクト
ParentBB pb = new ParentBB();
// 子クラスの継承メソッドと自己メソッド
System.out.println("結果1:" + pb.testA());
System.out.println("結果2:" + pb.testB());
// 暗黙的に型変換(子クラスオブジェクト ->親クラスオブジェクト変数名)
ParentAA pa = pb;
System.out.println("結果3:" + pa.testA());
}
}
package com.arkgame.study;
// 親クラス
class ParentAA {
public String testA() {
return "Parent class AAA";
}
}
// 子クラス
class ParentBB extends ParentAA {
public String testB() {
return "Child Class BBB";
}
}
public class ParentObjUse {
public static void main(String[] args) {
// 子クラスのオブジェクト
ParentBB pb = new ParentBB();
// 子クラスの継承メソッドと自己メソッド
System.out.println("結果1:" + pb.testA());
System.out.println("結果2:" + pb.testB());
// 暗黙的に型変換(子クラスオブジェクト ->親クラスオブジェクト変数名)
ParentAA pa = pb;
System.out.println("結果3:" + pa.testA());
}
}
package com.arkgame.study; // 親クラス class ParentAA { public String testA() { return "Parent class AAA"; } } // 子クラス class ParentBB extends ParentAA { public String testB() { return "Child Class BBB"; } } public class ParentObjUse { public static void main(String[] args) { // 子クラスのオブジェクト ParentBB pb = new ParentBB(); // 子クラスの継承メソッドと自己メソッド System.out.println("結果1:" + pb.testA()); System.out.println("結果2:" + pb.testB()); // 暗黙的に型変換(子クラスオブジェクト ->親クラスオブジェクト変数名) ParentAA pa = pb; System.out.println("結果3:" + pa.testA()); } }
実行結果
結果1:Parent class AAA
結果2:Child Class BBB
結果3:Parent class AAA