首页 > 解决方案 > java Super.call有什么最佳实践吗?

问题描述

    public boolean sendRequest(final Object... params) {
        if (!super.sendRequest(params)) {
            return false;
        }
        ...
        // Some Log code or tracing code here 
        ...

    }

为什么不实现一个新方法来调用 sendRequest 而不是覆盖?

    public boolean Send(final Object... params){
        if (!super.sendRequest(params)) {
            return false;
        }
        ...
        // Some Log code or tracing code here  
        ...

   }

标签: javasuper

解决方案


您是否希望具有覆盖的类能够以与原始类成员相同的方式使用?IE:

...
class MyClass extends TheirClass {
  @Override
  void doIt() {
    super.doIt();
    // also do my stuff
  }
}
...
// the doSomething function is part of the library where TheirClass lives.
// I can pass instances of MyClass to it, and doIt will be called, because MyClass IS-A TheirClass
theirFunction.doSomething(new MyClass(...));
...

但也许您只是想使用 的功能doIt,而不需要使用期望TheirClass.

在这种情况下,最好使用组合而不是继承:

class MyClass {
   private final TheirClass theirClass;

   public MyClass(TheirClass theirClass) {
     this.theirClass = theirClass;
   }

   public void doMyStuff() {
      theirClass.doIt();
      // and do some other things
   }
}

这比使用新方法名的继承要好,因为这样你就会在类上有两个方法做同样的事情(除了原来的 doIt 不做你的事情),并且可能不清楚应该调用哪个.

即使是覆盖方法的继承也可能有问题。我们不知道 TheyClass 中调用了什么代码doIt,所以我们添加的代码可能会在我们不期望的时候被调用。

总的来说,只要有可能,组合应该优先于继承。


推荐阅读