【发布时间】:2011-08-24 23:24:55
【问题描述】:
不确定这是否称为“方法隐藏”或“方法覆盖”,或者两者都不是,并且希望获得一些关于该主题的好文章。尤其是它是否是好的做法,何时以及何时不使用它,以及使用它的优点/缺点。
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),但我想知道是否有办法根据参数的子类来选择实现。由于参数是抽象类型,无法实例化,我必须传递一个子类作为参数。
【问题讨论】:
标签: java methods parameters overloading