简体   繁体   中英

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?

    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? 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 .

In that case it is probably better to use composition rather than 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.

Even inheritance where you override the method may have problems. 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.

Overall, composition should be preferred to inheritance whenever possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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