Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java Super.call有什么最佳实践吗?_Java_Super - Fatal编程技术网

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

java Super.call有什么最佳实践吗?,java,super,Java,Super,为什么不实现一个新方法来调用sendRequest而不是覆盖 public boolean sendRequest(final Object... params) { if (!super.sendRequest(params)) { return false; } ... // Some Log code or tracing code here ... } 是否希望具

为什么不实现一个新方法来调用sendRequest而不是覆盖

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

    }

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

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

   }
但是,也许您只想使用
doIt
的功能,而不需要使用需要
类的和代码

在这种情况下,可能最好使用组合而不是继承:

...
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不能做你的事情),而且可能不清楚应该调用哪个方法

即使重写方法的继承也可能有问题。我们不知道他们类中的代码调用了什么
doIt
,所以我们添加的代码可能会在我们不期望的时候被调用


总的来说,只要可能,组合就应该优先于继承。

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

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

   }
但是,也许您只想使用
doIt
的功能,而不需要使用需要
类的和代码

在这种情况下,可能最好使用组合而不是继承:

...
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不能做你的事情),而且可能不清楚应该调用哪个方法

即使重写方法的继承也可能有问题。我们不知道他们类中的代码调用了什么
doIt
,所以我们添加的代码可能会在我们不期望的时候被调用


总的来说,只要可能,组合就应该优先于继承。

我想这取决于覆盖
sendRequest()
方法的预期行为。如果它的行为或多或少与超级方法相同,并可能添加一些内容,则重写。如果您希望拥有引用但不知道对象具体类型的人能够调用该方法,则需要重写。如果不重写,那么我就不会在新方法的调用中提到super。只需
sendRequest(参数)
。以防有人引入覆盖。我想这取决于覆盖
sendRequest()
方法的预期行为。如果它的行为或多或少与超级方法相同,并可能添加一些内容,则重写。如果您希望拥有引用但不知道对象具体类型的人能够调用该方法,则需要重写。如果不重写,那么我就不会在新方法的调用中提到super。只需
sendRequest(参数)
。以防有人引入覆盖。