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

前端之家收集整理的这篇文章主要介绍了java – 如何在子类中强制实现一个方法而不使用抽象?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想强制子类实现一个我母亲类的实现方法.
我看这个 Java – Force implementation of an implemented method,但我不能把我的母亲类转换成抽象类.
  1. public class myMotherClass {
  2.  
  3. myMethod {
  4.  
  5. ...some code ..
  6.  
  7. }
  8.  
  9. }
  10.  
  11. public class myClass extends myMotherClass {
  12.  
  13. myMethod {
  14.  
  15. ... other code ...
  16. }
  17.  
  18. }

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

对不起我的英语不好…

解决方法

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

所以如果你不能使myMotherClass抽象,你只能引入另一个超类扩展myMotherClass并委托给必须实现的方法

  1. public abstract class EnforceImplementation extends myMotherClass {
  2.  
  3. public final void myMethod(){
  4. implementMyMethod();
  5. }
  6.  
  7. public abstract void implementMyMethod();
  8. }

编辑

我发现在hemcrest api中解决问题的另一种整合方式是例如.由mockito使用

  1. public interface Matcher<T> extends SelfDescribing {
  2.  
  3. /**
  4. * Evaluates the matcher for argument <var>item</var>.
  5. * <p/>
  6. * This method matches against Object,instead of the generic type T. This is
  7. * because the caller of the Matcher does not know at runtime what the type is
  8. * (because of type erasure with Java generics). It is down to the implementations
  9. * to check the correct type.
  10. *
  11. * @param item the object against which the matcher is evaluated.
  12. * @return <code>true</code> if <var>item</var> matches,otherwise <code>false</code>.
  13. *
  14. * @see BaseMatcher
  15. */
  16. boolean matches(Object item);
  17.  
  18. /**
  19. * This method simply acts a friendly reminder not to implement Matcher directly and
  20. * instead extend BaseMatcher. It's easy to ignore JavaDoc,but a bit harder to ignore
  21. * compile errors .
  22. *
  23. * @see Matcher for reasons why.
  24. * @see BaseMatcher
  25. */
  26. void _dont_implement_Matcher___instead_extend_BaseMatcher_();
  27. }

该接口指定一个方法_dont_implement_Matcher___instead_extend_BaseMatcher_.当然这并不妨碍其他人实现Matcher界面,但它会指导开发人员正确的方向.

BaseMatcher类实现_dont_implement_Matcher___instead_extend_BaseMatcher_方法为final

  1. public final void _dont_implement_Matcher___instead_extend_BaseMatcher_() {
  2. // See Matcher interface for an explanation of this method.
  3. }

最后我认为这是一个设计问题,因为BaseMatcher可以实现每个Matcher应该实现的逻辑.因此,使Matcher成为一个抽象类并使用模板方法是更好的办法.

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

猜你在找的Java相关文章