Question

I'm writing some Android code that need to utilize the inheritance feature. The following code snippet is the part that confused me:

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

And here is the 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);
    }
}

And if I used them in this way:

Bar bar = new Bar(1, 1, 1, 4);
System.out.println("The bar volume is : " + bar.getVolume());

Since in the getVolume() method, the SubClass Bar used the super.getVolume(), I'm wondering whether the answer is 1 * 2 * 3 + 4 = 10 or it's 1 * 1 * 1 + 4 = 5?

To be general, if the subclass called the SuperClass's method which needs to access some of the fields in the class, which class field will be used? Like in this example, if the super.getVolume() use the field in the SuperClass Foo, then it will return 1 * 2 * 3 = 6 and if it use the field in the SubClass Bar, the it will return 1 * 1 * 1 ?

Could someone help me clarify this and explain the reason in detail? Thanks in advance.

Was it helpful?

Solution

The super class will be created first (if you called super(,,) for sure) then the internalization of the field in the super class take place and in the end the field of the super class will be settled to the value assigned in sub class so

1*1*1+4=5

also this will not create two instance of the field one in the super and one in the sub , there will just one instance so saying which one will accessed is wrong.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top