Java:如何在重写方法(祖父方法)中调用super()。super() [英] Java: How to call super().super() in overridden method (grandparent method)

查看:843
本文介绍了Java:如何在重写方法(祖父方法)中调用super()。super()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

为什么是super.super.method();不允许使用Java?

我有3个类,它们彼此继承为如下:

I have 3 classes they inherit from each other as follows:

A
 ↳
   B
    ↳
     C

在每个课程中,我有以下方法:

Inside each class I have the following method:

protected void foo() {
    ...
}

内部课程 C 我想从课程 A < c>中调用 foo / code>未在 B 中调用 foo

Inside class C I want to call foo from class A without calling foo in B:

protected void foo() {
    // This doesn't work, I get the following compile time error:
    // Constructor call must be the first statement in a constructor
    super().super().foo(); 
}

编辑

上下文信息:

B类是我们使用的实际类。 C类是一个单元测试类,它有一些修改。 foo B 内的方法做了一些我们不想要的事情,所以我们在 C里面覆盖它。但是 A
中的 foo 非常有用,需要调用。

EDIT
Some Context Info:
Class B is an actual class we use. Class C is a unit test class, it has some modifications. foo method inside B does some things we don't want so we override it inside C. However foo in class A is useful and needs to be called.

推荐答案


  • 要调用超类中的方法,请使用 super.foo() ,而不是 super()。foo() super()调用父类的构造函数。

  • 无法调用 super.super包含.foo()。您可以在B类中添加对 super.foo()的调用,以便调用 super.foo() in C,将在B中调用 super.foo(),然后在A中调用 foo()

    • To call a method in a super class, you use super.foo(), not super().foo(). super() calls the constructor of the parent class.
    • There is no way to call super.super.foo(). You can add a call to super.foo() in class B, so that calling super.foo() in C, will call super.foo() in B which in turn will call foo() in A.
    • 这篇关于Java:如何在重写方法(祖父方法)中调用super()。super()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆