简体   繁体   中英

Can I call an overridden method from the super of the super?

Assume that I have these three classes:

class Foo {
    void fn() {
        System.out.println("fn in Foo");
    }
}

class Mid extends Foo {
    void fn() {
        System.out.println("fn in Mid");
    }
}

class Bar extends Mid {
    void fn() {
        System.out.println("fn in Bar");
    }

    void gn() {
        Foo f = (Foo) this;
        f.fn();
    }
}

public class Trial {
    public static void main(String[] args) throws Exception {
        Bar b = new Bar();
        b.gn();
    }
}

Is it possible to call a Foo 's fn() ? I know that my solution in gn() doesn't work because this is pointing to an object of type Bar .

It's not possible in Java. You can use super but it always uses the method in immediate superclass in type hierarchy.

Also note that this:

Foo f = (Foo) this;
f.fn();

is the very definition of polymoprhism how virtual call works: even though f is of type Foo , but at runtime f.fn() is dispatched to Bar.fn() . Compile-time type doesn't matter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM