[英]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
對象,並在Cat
和Mouse
子類中使用重載的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)
,但是我想知道是否有一種方法可以根據參數的子類來選擇實現。 由於參數是抽象類型且無法實例化,因此我必須將子類作為參數傳遞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.