を実装する必要があります。抽象化することによってメソッドを実装するように強制することはできます。だから、
あなたが唯一実施されなければならない方法にmyMotherClassとデリゲートを拡張し、別のスーパークラスを導入することができmyMotherClassが抽象作ることができない場合:
public abstract class EnforceImplementation extends myMotherClass {
public final void myMethod(){
implementMyMethod();
}
public abstract void implementMyMethod();
}
EDIT
私は別の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
クラスは最後に、私はBaseMatcher
がobviouoslyすべてのMatcher
が実装すべきロジックを実装しているため、これは、設計上の問題だと思い最終
public final void _dont_implement_Matcher___instead_extend_BaseMatcher_() {
// See Matcher interface for an explanation of this method.
}
として_dont_implement_Matcher___instead_extend_BaseMatcher_
メソッドを実装します。したがって、Matcher
を抽象クラスにしてテンプレートメソッドを使用する方が良いでしょう。
しかし、私はバイトコードの互換性と新機能の最適な妥協であったので、彼らはそれをしたと思います。あなたが受け入れテストのいくつかのフォームを持っていなければならないよう
public class MyMotherClass {
public void myMethod() {
throw new RuntimeException("Method not overwritten");
}
}
は、ほとんどの場合、これは、十分なはずです。(私はコメントで、それへの言及を見ましたが)ほとんどの人が見渡せている
要約:抽象化せずにできない –
@stonedsquirrelインターフェイスについてはどうですか? –
アノテーションを使用したり、クラスがメソッドを実装していない場合は例外をスローすることはできません。 – Maniz