强制重写非抽象方法 [英] Force non-abstract method to be overridden
问题描述
我在一个抽象类中有一个方法 String foo()
,它已经进行了一些预计算,但无法提供该方法应该返回的最终结果。所以我想要的是,从我的抽象类继承的每个非抽象类必须以第一个 super()$的方式实现
foo
调用c $ c>然后计算结果。有没有办法在java中强制执行此操作?
I have a method String foo()
in an abstract class which already does a few precomputations but can't deliver the final result the method is supposed to return. So what I want is that each non-abstract class inheriting from my abstract class has to implement foo
in a way that first super()
is called and then the result is computed. Is there a way to force this in java?
推荐答案
是的,通过重新设计使用模板方法模式并包含一个抽象方法:
Yes, by redesigning to use the template method pattern and including an abstract method:
public abstract class AbstractSuper {
public final String foo() {
// Maybe do something before calling bar...
String initialResult = bar();
// Do something common, e.g. validation
return initialResult;
}
protected abstract String bar();
}
基本上如果要强制子类覆盖方法,它 必须是抽象的 - 但这不一定是其他代码调用的方法...
Basically if you want to force subclasses to override a method, it does have to be abstract - but that doesn't have to be the method that is called by other code...
这篇关于强制重写非抽象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!