如果子类调用超类方法,将使用Java谁的字段

时间:2013-06-13 15:15:58

标签: java inheritance override class-members

我正在编写一些需要利用继承功能的Android代码。以下代码片段让我感到困惑:

SuperClass:

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;
    }
}

这是SubClass:

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?

有人可以帮我澄清一下并详细解释原因吗?提前谢谢。

1 个答案:

答案 0 :(得分:0)

首先创建超类(如果你肯定称为super(,,))那么超类中字段的内部化就会发生,最后超类的字段将被设置为值在子类中分配,所以

1*1*1+4=5

这也不会在super中创建一个字段实例,在sub中创建一个实例,只有一个实例,所以说哪个将被访问是错误的。