【问题标题】:Recursively call function on super递归调用超级函数
【发布时间】:2013-08-29 22:43:11
【问题描述】:

我想在 super 上递归调用一个方法,以便将调用的方法传播到最后一个超类。这个伪代码告诉我想做什么,但当然这不能用 Java 编译。

public MyClass {

    protected void method() {

        // do something on this level

        if (super instanceof MyClass) {
            MyClass superLevel = (MyClass) super;
            superLevel.method();
        }
    }
}

如何实现这种行为?

【问题讨论】:

  • 这段代码必须放在超类中。在超类中,你可以写if (this instance of MyClass),但恕我直言,它暴露了一个设计缺陷:超类不应该知道它的子类。
  • 唯一的选择是在每个级别上添加super.method() 呼叫。您只能使用super 调用直接超类方法。

标签: java inheritance superclass super


【解决方案1】:

你可以使用:

public class MySuperClass {
    protected void method() {
         // Whatever you want to do in super class
    }
}

public class MyClass extends MySuperClass {
    @Override
    protected void method() {
         // Whatever you want to do in this specific class

         // Call super.method
         super.method();
    }
}

您可以在一系列类中以这种方式使用它。

【讨论】:

  • 为什么不加解释就投反对票?
  • 忽略它们,没有有效的。继续帮助:)
【解决方案2】:

在您也可以编辑所有这些类之前,您不能直接这样做。直接只能使用直接父级的方法,不能高于此。

如果您可以编辑父母,请在每个级别致电super.method()

【讨论】:

    猜你喜欢
    • 2012-01-04
    • 2015-08-12
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多