微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

原文地址:https://www.jb51.cc/java/122047.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐