如何在不使用抽象的情况下强制实现子类中的方法?

Man*_*niz 16 java methods class abstract implements

我想强制子类实现我母类的实现方法.我看这个Java - 强制实现一个已实现的方法,但我无法将我的母类转换为抽象类.

public class myMotherClass { 

   myMethod {

      ...some code ..

   }

}

public class myClass extends myMotherClass {

   myMethod {

      ... other code ...
   }

}
Run Code Online (Sandbox Code Playgroud)

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

对不起我的英语不好...

Ren*_*ink 18

您不能强制子类覆盖方法.您只能通过将其抽象化来强制它实现方法.

因此,如果你不能创建myMotherClass抽象,你只能引入另一个扩展myMotherClass的超类,并委托给必须实现的方法:

public abstract class EnforceImplementation extends myMotherClass {

        public final void myMethod(){
             implementMyMethod();
        }

        public abstract void implementMyMethod();
}
Run Code Online (Sandbox Code Playgroud)

编辑

我找到了另一种解决hemcrestapi 问题的有效方法,例如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_();
}
Run Code Online (Sandbox Code Playgroud)

接口指定方法_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.
}
Run Code Online (Sandbox Code Playgroud)

最后我认为这是一个设计问题,因为BaseMatcher显而易见地实现了每个Matcher应该实现的逻辑.因此,制作Matcher抽象类并使用模板方法会更好.

但我猜他们这样做是因为它是字节码兼容性和新功能之间的最佳折衷方案.


Kar*_*k T 6

您可以重新设计层次结构,以便您的具体类只是树的叶子.

代替

myClass extends myMotherClass
Run Code Online (Sandbox Code Playgroud)

考虑

myClass extends myMotherAbstractClass
myMotherClass extends myMotherAbstractClass 
Run Code Online (Sandbox Code Playgroud)

这样,Abstract类由两个实例化的类继承.在这种情况下,它可能myMotherClass会非常薄,只是执行myMethod.


bnu*_*mak 5

大多数人忽略的一件事是以下实现(尽管我在评论中看到了它):

public class MyMotherClass { 

    public void myMethod() {
      throw new RuntimeException("Method not overwritten");
    }    

}
Run Code Online (Sandbox Code Playgroud)

在大多数情况下,这应该足够了,因为您应该进行某种形式的验收测试(即使它只是手动测试继承类)。从理论上讲,您仍然在引入一种可能性,即没有人会意识到该方法直到生产才被覆盖。