繁体   English   中英

java Super.call 是否有任何最佳实践?

[英]Is there any best practice on 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  
        ...

   }

您是否希望您的 class 能够以与原始 class 成员相同的方式使用? 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的代码。

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

class MyClass {
   private final TheirClass theirClass;

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

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

这比具有新方法名称的 inheritance 更好,因为这样您将在 class 上有两种方法,它们做同样的事情(除了原始 doIt 不做你的事情),并且可能不清楚应该调用哪个.

即使您覆盖该方法的 inheritance 也可能有问题。 我们不知道 TheyClass 中的哪些代码调用了doIt ,所以我们添加的代码可能会在我们不期望的时候被调用。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM