java - 我可以从 super 的 super 调用重写的方法吗?

标签 java inheritance polymorphism dynamic-binding

假设我有这三个类:

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 中是不可能的。您可以使用 super,但它始终使用类型层次结构中直接父类(super class)中的方法。

另请注意:

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

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

关于java - 我可以从 super 的 super 调用重写的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8281057/

相关文章:

perl - 如何重新分类 Perl 对象

c++ - 用于访问多态类型的 std::visit-like 函数

c++ 如何测试一个类以查看它是否有成员?

java - 如何找到java非阻塞方法的执行时间

java - 如何使用 mongodb-java-driver 进行 upsert

java - 自动适应添加到 SashForm 运行时的 Composite

c# - 是否可以继承 XAML?

Java:不能泛型 List<?扩展父> mylist

c# - SQL Server 中多态树的数据模式和查询

java - fragment 不兼容的类型错误