gpt4 book ai didi

java - 需要重写方法来调用 super

转载 作者:IT老高 更新时间:2023-10-28 21:11:41 24 4
gpt4 key购买 nike

我希望当子类覆盖父类中的方法时,在该子方法中调用 super.method()

有没有办法在编译时检查这个?
如果没有,发生这种情况时我将如何抛出运行时异常?

最佳答案

没有办法直接要求这个。但是,您可以做的是:

public class MySuperclass {
public final void myExposedInterface() {
//do the things you always want to have happen here

overridableInterface();
}

protected void overridableInterface() {
//superclass implemention does nothing
}
}

public class MySubclass extends MySuperclass {
@Override
protected void overridableInterface() {
System.out.println("Subclass-specific code goes here");
}
}

这提供了一个内部接口(interface)点,子类可以使用该接口(interface)点向公共(public) myExposedInterface() 方法添加自定义行为,同时确保无论子类做什么,都始终执行父类(super class)行为。

关于java - 需要重写方法来调用 super,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6853638/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com