您不能强制子类覆盖方法。您只能通过使其抽象来强制它实现方法。
所以如果你不能使 myMotherClass 抽象,你只能引入另一个超类来扩展 myMotherClass 并委托给必须实现的方法:
public abstract class EnforceImplementation extends myMotherClass {
public final void myMethod(){
implementMyMethod();
}
public abstract void implementMyMethod();
}
编辑
我在hemcrest api 中找到了另一种解决问题的有趣方法,例如由 mockito 使用。
public interface Matcher<T> extends SelfDescribing {
/**
* Evaluates the matcher for argument <var>item</var>.
* <p/>
* This method matches against Object, instead of the generic type T. This is
* because the caller of the Matcher does not know at runtime what the type is
* (because of type erasure with Java generics). It is down to the implementations
* to check the correct type.
*
* @param item the object against which the matcher is evaluated.
* @return <code>true</code> if <var>item</var> matches, otherwise <code>false</code>.
*
* @see BaseMatcher
*/
boolean matches(Object item);
/**
* This method simply acts a friendly reminder not to implement Matcher directly and
* instead extend BaseMatcher. It's easy to ignore JavaDoc, but a bit harder to ignore
* compile errors .
*
* @see Matcher for reasons why.
* @see BaseMatcher
*/
void _dont_implement_Matcher___instead_extend_BaseMatcher_();
}
接口指定了一个方法_dont_implement_Matcher___instead_extend_BaseMatcher_。当然它并不妨碍其他人实现Matcher 接口,但它引导开发者朝着正确的方向前进。
而BaseMatcher 类将_dont_implement_Matcher___instead_extend_BaseMatcher_ 方法实现为final
public final void _dont_implement_Matcher___instead_extend_BaseMatcher_() {
// See Matcher interface for an explanation of this method.
}
最后我认为这是一个设计问题,因为BaseMatcher 显然实现了每个Matcher 都应该实现的逻辑。因此,最好将Matcher 设为抽象类并使用模板方法。
但我猜他们这样做是因为这是字节码兼容性和新功能之间的最佳折衷。