JAVA

フィールドの継承

先ほど書いた実験コードに、フィールドが継承されるかどうかの検証をしてみます。

以下のようなコードを書いてみました。
[c]
public class SuperClassTest3{

public static void main(String[] args) {

//オブジェクトのインスンタンスを生成する
TestClassChild tcc = new TestClassChild();

System.out.println(tcc.TestA);
System.out.println(tcc.TestB);

//tcc.PrintTextC();
//tcc.PrintTextP();

}
}

class TestClassChild extends TestClassParent
{
TestClassChild() {
//引数なしコンストラクタ用

}

void PrintTextC() {
System.out.print("PrintTextC !! \n");
}

void PrintTextP() {
System.out.print("PrintTextP オーバーライドテスト !! \n");
}

}

class TestClassParent
{
int TestA = 10;
int TestB = 20;

TestClassParent() {
//引数なしコンストラクタ用

}

void PrintTextP() {
System.out.print("PrintTextP !! \n");
}

}

[/c]

結果は下記のようになり、親クラスのTestA、TestBというフィールドの値を参照することができています。

[c]
10
20
[/c]

■注意■
フィールドとメソッドは継承元(親クラス)のものが参照できますが、コンストラクタは継承されず、使うことができません。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です