你不能強迫一個子類覆蓋的方法。你只能強制它通過抽象來實現一個方法。
所以,如果你不能讓myMotherClass抽象的,你只能引入擴展myMotherClass和代表們必須實現該方法的另一超:
public abstract class EnforceImplementation extends myMotherClass {
public final void myMethod(){
implementMyMethod();
}
public abstract void implementMyMethod();
}
編輯
我發現了另一個interessting方式解決問題的例子是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_
方法,最終
public final void _dont_implement_Matcher___instead_extend_BaseMatcher_() {
// See Matcher interface for an explanation of this method.
}
最後,我認爲這是一個設計問題,因爲BaseMatcher
obviouosly實現了每一個Matcher
應該實現的邏輯。因此,將Matcher
作爲抽象類並使用模板方法會更好。
但我想他們這樣做是因爲這是字節碼兼容性和新功能之間的最佳折衷。
總之:你不能沒有抽象 –
@stonedsquirrel接口怎麼樣? –
如果類沒有實現該方法,那麼使用註釋或拋出異常是不可能的? – Maniz