継承機能を利用する必要がある Android コードをいくつか書いています。次のコード スニペットは、私を混乱させた部分です。
スーパークラス:
public class Foo {
public int length = 1;
public int width = 2;
public int height = 3;
public Foo(int len, int wid, int hei)
{
length = len;
width = wid;
height = hei;
}
public int getVolume()
{
return length * width * height;
}
}
サブクラスは次のとおりです。
public class Bar extends Foo {
int extraVolume = 4;
public Bar(int len, int wid, int hei, int extra)
{
super(len, wid, hei);
length = len;
width = wid;
height = hei;
this.extraVolume = extra;
}
@Override
public int getVolume()
{
return (super.getVolume() + this.extraVolume);
}
}
そして、私がそれらをこのように使用した場合:
Bar bar = new Bar(1, 1, 1, 4);
System.out.println("The bar volume is : " + bar.getVolume());
getVolume() メソッドで SubClass Bar が super.getVolume() を使用したので、答えが 1 * 2 * 3 + 4 = 10 なのか、それとも 1 * 1 * 1 + 4 = 5 なのか疑問に思っています。
一般的に、サブクラスが、クラス内のいくつかのフィールドにアクセスする必要がある SuperClass のメソッドを呼び出した場合、どのクラス フィールドが使用されますか? この例のように、super.getVolume() が SuperClass Foo のフィールドを使用すると、1 * 2 * 3 = 6 が返され、SubClass Bar のフィールドを使用すると、1 * 1 * が返されます。 1 ?
誰かがこれを明確にし、理由を詳細に説明するのを手伝ってくれませんか? 前もって感謝します。