簡體   English   中英

使用子類參數隱藏方法

[英]Hiding methods with a subclass parameter

不知道這是所謂的“方法隱藏”還是“方法替代”,或者都不是,並且是否希望直接閱讀有關該主題的好文章。 特別是,它是否是一種好的做法,何時以及何時不使用它,以及使用它的優點/缺點。

public class Animal {

  /* constructor */
  Animal () { }

  /* instance method */
  void add(Number n) {
    System.out.println("An animal added a number!");
  }

  /* Main method */
  public static void main(String[] args) {
    Integer i = 2;   // Integer i = new Integer(2);
    Double d = 3.14; // Double d = new Double(3.14);

    Animal mammal = new Animal();
    Cat tom = new Cat();
    Mouse jerry = new Mouse();

    mammal.add(i); // produces "An animal added a number!"
    mammal.add(d); // produces "An animal added a number!"

    tom.add(i);    // produces "Tom added an integer!"
    tom.add(d);    // produces "An animal added a number!"

    jerry.add(i);  // produces "An animal added a number!"
    jerry.add(d);  // produces "Jerry added a double!"
  }
}

class Cat extends Animal {

  /* constructor */
  Cat () { }

  /* instance method */
  void add(Integer i) {
    // param of type Integer extends Number
    System.out.println("Tom added an integer!");
  }
}

class Mouse extends Animal {

  /* constructor */
  Mouse () { }

  /* instance method */
  void add(Double d) {
    // param of type Double extends Number
    System.out.println("Jerry added a double!");
  }
}

編輯:

感謝@MByD,發現這稱為“方法重載”。

與上述相關的新問題:在Animal類中,我想創建一個方法,該方法采用Number對象,並在CatMouse子類中使用重載的add()方法之一。 是否有比下面顯示的方法更好的方法?

public class Animal {
...
  void subtract(Number n) {
    if      (n instanceof Integer) this.add(-(Integer) n); // from the Cat class
    else if (n instanceof Double)  this.add(-(Double) n);  // from the Mouse class
    ...
  }
...
}

是的,我意識到我可以只寫this.add(-n) ,但是我想知道是否有一種方法可以根據參數的子類來選擇實現。 由於參數是抽象類型且無法實例化,因此我必須將子類作為參數傳遞。

這稱為方法重載,因為方法的簽名不同。

請參見Java方法教程

Java編程語言支持重載方法,Java可以區分具有不同方法簽名的方法。 這意味着,如果類中的方法具有不同的參數列表,則它們可以具有相同的名稱(對此有一些限定條件,將在標題為“接口與繼承”的課程中進行討論)。

是否以及何時使用各種重載/重載/重影等爭論是一個很大的爭論。 約書亞·布洛赫(Joshua Bloch)所著的《 有效的Java》是一本很好的資源。 我發現這非常有用和有趣。

暫無
暫無

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

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