强制覆盖非抽象方法 [英] Force non-abstract method to be overridden
问题描述
我在抽象类中有一个方法 String foo()
,它已经做了一些预计算,但无法提供该方法应该返回的最终结果.所以我想要的是,从我的抽象类继承的每个非抽象类都必须以先调用 super()
然后计算结果的方式实现 foo
.有没有办法在java中强制这样做?
是的,通过重新设计以使用 模板方法模式并包括一个抽象方法:
公共抽象类 AbstractSuper {公共最终字符串 foo() {//也许在调用 bar 之前做一些事情...String initialResult = bar();//做一些常见的事情,例如验证返回初始结果;}受保护的抽象字符串 bar();}
基本上,如果你想强制子类覆盖一个方法,它确实必须是抽象的——但这不一定是被其他代码调用的方法......>
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屋!