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

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

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 extends SelfDescribing { /** * Evaluates the matcher for argument item. * 

* 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 true if item matches, otherwise false. * * @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设为抽象类并使用模板方法。

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

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

代替

 myClass extends myMotherClass 

考虑

 myClass extends myMotherAbstractClass myMotherClass extends myMotherAbstractClass 

这样,Abstract类由两个实例化的类inheritance。 在这种情况下, myMotherClass很可能非常薄,只是myMethod的实现。

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

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

在大多数情况下,这应该足够了,因为您应该进行某种forms的验收测试(即使它只是手动测试inheritance类)。 从理论上讲,你仍然有可能没有人会意识到这种方法在生产之前并没有被覆盖。

如果你真的想强制实现方法使用应该使用interface

 public interface MyInterface{ void myMethod(); } 

现在,如果有人希望在MyClass implements MyInterface从这个接口MyClass implements MyInterface ,你必须实现myMethod();

 public MyClass implements MyInterface{ public void myMethod{ // do something } }