java – 如何在子类中强制实现一个方法而不使用抽象?

我想强制子类实现一个我母亲类的实现方法.
我看这个 Java – Force implementation of an implemented method,但我不能把我的母亲类转换成抽象类.
public class myMotherClass { 

   myMethod {

      ...some code ..

   }

}

public class myClass extends myMotherClass {

   myMethod {

      ... other code ...
   }

}

所以,在这个例子中,我想强制myClass实现myMethod.

对不起我的英语不好…

解决方法

你不能强制一个子类覆盖一个方法.你只能强制它通过抽象来实现一个方法.

所以如果你不能使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成为一个抽象类并使用模板方法是更好的办法.

但是我猜他们是这样做的,因为它是字节码兼容性和新功能之间最好的妥协.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...