簡體   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