Search code examples
javamultiple-inheritance

does super only go one level above?


if I have:

class Zero {
    int n = 0;

    void setN(int x) {
        n += x;
    }
}

class One extends Zero {
    int n = 1;

    void setN(int x) {
        n += x;
        super.setN(x);
    }

}

class Two extends One {
    int n = 2;

    void setN(int x) {
        n += x;
        super.setN(x);
    }

    void show() {
        System.out.println(n);
        System.out.println(super.n);
        // System.out.println(super.super.n);   error

    }

    public static void main(String[] args) {
        Two two = new Two();
        two.show();
        // >>>
        // 2
        // 1

        two.setN(1);
        two.show();
        // >>>
        // 3
        // 2
    }
}

I re-edited it, with a method setN pass down from Zero. It worked, so does it mean that I can still 'change' the n in Zero, but I just won't see it?

It is also very interesting that even though setN is exactly the same in One and Two, I have to manually override it, if I delete setN in Two, this will behave differently. The setN won't change n in Two.

It seems that super can only go one level above? Is there anyway to call n in zero?

But the other question is that if I intended to override int n in subclass, why is it allow me to visit n in parent at all?

Thanks,


Solution

  • It's not possible in Java unlike C++ which supports it using scope resolution.

    You could have a method

    int getZeroN(){
        return n;
    }
    

    in your Zero and then call it using System.out.println(super.getZeroN()); from Two