【问题标题】:Can I call an overridden method from the super of the super?我可以从 super 的 super 调用覆盖的方法吗?
【发布时间】:2011-11-26 19:40:43
【问题描述】:

假设我有这三个类:

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

是否可以调用Foofn()?我知道我在gn() 中的解决方案不起作用,因为this 指向Bar 类型的对象。

【问题讨论】:

  • 这还能编译吗?
  • 当然!!有什么问题??
  • 我忽略了方法是私有的

标签: java inheritance polymorphism dynamic-binding


【解决方案1】:

这在 Java 中是不可能的。您可以使用super,但它始终使用类型层次结构中直接超类中的方法。

还要注意:

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

正是 polymoprhism 虚拟调用如何工作的定义:即使f 的类型为Foo,但在运行时f.fn() 被分派到Bar.fn()。编译时类型无关紧要。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-09
    • 2012-05-01
    • 2023-01-07
    • 2013-10-24
    • 1970-01-01
    • 2011-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多