LoginSignup
2

More than 3 years have passed since last update.

[Java] 子クラスのインスタンスを親クラスに型変換する場合の注意点

Last updated at Posted at 2019-06-27

Parent p = new Child()Child c = new Child() で何が異なるのか備忘録

注意点

  • 変数はstaticかどうかにかかわらず、参照型のクラス("="の左側)が優先される。
  • メソッドは、staticであれば、参照型のクラス("="の左側)が優先される。

想定ケース

  • Childクラスの親クラスがParentクラス
  • staticと非staticなメンバとメソッドが各クラスでそれぞれ定義されている。
class Parent{
    int a = 1;
    static int b = 2;

    String medhod1() {
        return "parent method1";
    }

    static String medhod2() {
        return "parent method2";
    }
}


class Child extends Parent{
    int a = 10;
    int b = 20;

    @Override
    String medhod1() {
        return "child method1";
    }

    static String medhod2() {
        return "child method2";
    }
}

実行結果

        Parent parent = new Child();

        System.out.println(parent.a); // => 1 ・・・★
        System.out.println(parent.b); // => 2 ・・・★
        System.out.println(parent.medhod1());  // => child method1  ・・・★
        System.out.println(parent.medhod2());  // => parent method2

        Child child = new Child();
        System.out.println(child.a);  // => 10
        System.out.println(child.b);  // => 20
        System.out.println(child.medhod1());  // => child method1
        System.out.println(child.medhod2());  // => child method1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2