簡體   English   中英

重寫方法時調用超類的方法的目的是什么?

[英]What is the purpose of calling super class's method while overriding a method?

在從AsyncTask覆蓋onPostExecute等方法時,我們可以避免或刪除super.onPostExecute(result); 從中。 你能告訴我為什么以及什么時候需要使用這個調用嗎? 因為我在這里將 AsyncTask 實現為我的主要活動中的內部 class

    private class CustomAsyncTask extends AsyncTask<String, Void, Event> {
    @Override
    protected Event doInBackground(String... strings) {
        Event result = Utils.fetchEarthquakeData(strings[0]);
        return result;
    }

    @Override
    protected void onPostExecute(Event result) {
        super.onPostExecute(result);// what is the effect of calling this? If it was possible to skip or remove it. 
        updateUi(result);
    }
    
}

當您覆蓋一個方法時,您重新定義了該方法,即如果在子 class 的實例上調用此方法(您已在其中覆蓋了該方法),則將調用該新版本的定義。

當您覆蓋一個方法時(即重新定義或換句話說,用子定義的版本替換超類定義),您有兩種選擇:

  1. 不要使用超類定義中的任何內容並以全新的方式重寫它。
  2. 在新定義的某個點(開始/中間/結束)重用超類定義。 這就像在冰淇淋蛋筒上放一顆櫻桃,其中冰淇淋蛋筒是該方法的超類定義,而新定義中添加了櫻桃。

請注意,正如Andy Turner已經指出的那樣,調用 super的要求被認為是一種反模式。

當我們覆蓋某些方法時,這意味着:

  1. 我們的項目中有接口。
  2. 在該界面中,一個 Class 是父級,另一個是子級。

現在覆蓋意味着在父母和孩子中都有相同的方法。 以下示例:

class Parent
{

 public Parent()
 {
  "Inside Parent Constructor";
 }
 
 public void meth()
 {
  "Inside Parent Method";
 }

}

class Child
{

 public Child()
 {
  "Inside Child Constructor";
 }
 
 public void meth()
 {
  super();              
  "Inside Parent Method";
 }

}

由於 Child Class 中的 super 關鍵字,它將 go 到 Parent 的構造函數。 並打印“內部父構造函數”。

所以主要的事情是,很多時候Andoid OS 會想要訪問父Class 方法被覆蓋,為此我們編寫了super()。

重寫方法時調用超類的方法的目的是什么?

The purpose is to run the method in the class from which the current class inherits from to perform some work that class is responsible, as it could be some setup of the super class' state.

對於您的特定情況,無需調用 super.onPostExcecute() ,如下面的問題所述:

我應該在 Android AsyncTask 中調用 super.onPostExecute(result) 嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM