I'm fairly new to Java and would like to know how to accomplish the following task, and also, whether it is considered bad style, even if it is possible. Thank you.
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.
But can I now get Fish's swim() method to be invoked, using the same "f.swim()
" syntax?
// 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:
Re: answers, thanks people! Regarding SO user Rinke's answer below - he states that "You can assign your tuna instance to both tuna and fish typed variables, but it'll always be a tuna."
The last part of that sentence got my novice OOD brain wondering - why allow a "super object" to refer to a "sub object" anyway? What is the benefit of this flexibility? What benefit is there in allowing a Fish object the ability to "switch between" referring to either a fish or a tuna? Thank you.
Edit 2:
Here is some example code to illustrate the concept of SO user Rinke's "answer to edit" response, below.
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();
}