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

oogrdqng  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(484)
  1. public boolean sendRequest(final Object... params) {
  2. if (!super.sendRequest(params)) {
  3. return false;
  4. }
  5. ...
  6. // Some Log code or tracing code here
  7. ...
  8. }

为什么不实现一个新方法来调用sendrequest而不是重写?

  1. public boolean Send(final Object... params){
  2. if (!super.sendRequest(params)) {
  3. return false;
  4. }
  5. ...
  6. // Some Log code or tracing code here
  7. ...
  8. }
pexxcrt2

pexxcrt21#

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

  1. ...
  2. class MyClass extends TheirClass {
  3. @Override
  4. void doIt() {
  5. super.doIt();
  6. // also do my stuff
  7. }
  8. }
  9. ...
  10. // the doSomething function is part of the library where TheirClass lives.
  11. // I can pass instances of MyClass to it, and doIt will be called, because MyClass IS-A TheirClass
  12. theirFunction.doSomething(new MyClass(...));
  13. ...

但也许你只是想使用 doIt ,但不需要使用 TheirClass .
在这种情况下,最好使用组合而不是继承:

  1. class MyClass {
  2. private final TheirClass theirClass;
  3. public MyClass(TheirClass theirClass) {
  4. this.theirClass = theirClass;
  5. }
  6. public void doMyStuff() {
  7. theirClass.doIt();
  8. // and do some other things
  9. }
  10. }

这比用新方法名继承要好,因为这样类上就有两个方法做同样的事情(除了原来的doit不做你的工作),而且可能不清楚应该调用哪一个。
即使重写方法的继承也可能有问题。我们不知道他们的类调用中有什么代码 doIt ,所以我们添加的代码可能会在我们不希望的时候被调用。
总的来说,只要可能,组合应该优先于继承。

展开查看全部

相关问题