java super.call有什么最佳实践吗?

oogrdqng  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(431)
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  
        ...

   }
pexxcrt2

pexxcrt21#

是否希望具有重写的类能够以与原始类的成员相同的方式使用?即。:

...
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不做你的工作),而且可能不清楚应该调用哪一个。
即使重写方法的继承也可能有问题。我们不知道他们的类调用中有什么代码 doIt ,所以我们添加的代码可能会在我们不希望的时候被调用。
总的来说,只要可能,组合应该优先于继承。

相关问题