我对 Java 相当陌生,想知道如何完成以下任务,以及它是否被认为是不好的风格,即使它是可能的。谢谢。
Fish f; // Fish is a superclass,
Tuna t = new Tuna(); // to which Tuna is a subclass.
f=t; // the Fish object "f" now refers to the Tuna object "t".
// Both Fish and Tuna have an identical method (signature wise) called swim() ,
f.swim(); // and so Tuna's overridden swim() method is invoked here.
但是我现在可以使用相同的“来调用 Fish 的 Swim() 方法吗?”f.swim()
“ 句法?
// I would now like Fish's swim() method to be invoked here,
// but is it bad style and/or am I missing some point about OOP?
f.swim();
Edit:
回复: 各位解答,谢谢!关于 SO 用户 Rinke 下面的回答 - 他指出“您可以将金枪鱼实例分配给金枪鱼和鱼类型变量,但它始终是金枪鱼。”
这句话的最后一部分让我的 OOD 新手大脑感到疑惑 - 为什么要允许“超级对象”引用“子对象”?这种灵活性有什么好处?允许 Fish 对象能够在指鱼或金枪鱼之间“切换”有什么好处?谢谢。
Edit 2:
下面是一些示例代码,用于说明 SO 用户 Rinke 的“编辑答案”响应的概念。
Bear b = new Bear();
Fish f = getAnyFish();
b.eat(f);
Fish getAnyFish(){
//To toggle the returned fish type, change true to false
if (true) return new Tuna();
else return new Salmon();
}