加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 05:35:29 所属栏目:Java 来源:网络整理
导读:我想强制子类实现一个我母亲类的实现方法. 我看这个 Java – Force implementation of an implemented method,但我不能把我的母亲类转换成抽象类. public class myMotherClass { myMethod { ...some code .. }}public class myClass extends myMotherClass {
我想强制子类实现一个我母亲类的实现方法.
我看这个 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成为一个抽象类并使用模板方法是更好的办法.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读