[英]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.