简体   繁体   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 
        ...

    }

Why not implement a new method to call sendRequest rather than overwrite?为什么不实现一个新方法来调用 sendRequest 而不是覆盖?

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

   }

Do you want your class with the override to be able to be used in the same way as members of the original class?您是否希望您的 class 能够以与原始 class 成员相同的方式使用? ie: 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(...));
...

But perhaps you just want to use the functionality of doIt , but don't need to use and code which expects a TheirClass .但也许你只是想使用doIt的功能,而不需要使用和需要一个TheirClass的代码。

In that case it is probably better to use composition rather than inheritance:在这种情况下,最好使用组合而不是 inheritance:

class MyClass {
   private final TheirClass theirClass;

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

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

This is better than inheritance with a new method name, because then you would have two methods on the class which do about the same thing (except the original doIt doesn't do your stuff), and it may not be clear which should be called.这比具有新方法名称的 inheritance 更好,因为这样您将在 class 上有两种方法,它们做同样的事情(除了原始 doIt 不做你的事情),并且可能不清楚应该调用哪个.

Even inheritance where you override the method may have problems.即使您覆盖该方法的 inheritance 也可能有问题。 We don't know what code in TheirClass calls doIt , so perhaps the code we've added will be called when we don't expect it to be.我们不知道 TheyClass 中的哪些代码调用了doIt ,所以我们添加的代码可能会在我们不期望的时候被调用。

Overall, composition should be preferred to inheritance whenever possible.总的来说,只要有可能,组合应该优先于 inheritance。

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

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