This page contains an archived post to the Design Forum (formerly called the Flexible Java Forum) made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Polymorphism & dynamic binding question
Posted by Chris Laird on 19 Feb 1999, 2:42 AM
Here's a little problem I've been trying to solve.
I have an abstract base class with two concrete subclasses.
For the sake of simplicity, let's go back to the same old
abstract class Animal ...
class Dog extends Animal ...
class Cat extends Animal ...
Right, I want to write a method which does something with
Animals, but does a different thing with Dogs than Cats.
Trying to avoid using instanceof and downcasting, I wanted
to use overloaded methods, one method for each specific
type of animal that I need to handle:
void buy(Cat c) ...
void buy(Dog d) ...
So far so good. But in my client code, I store references
to Dogs and Cats as Animals because I don't know exactly
what type of Animal might be coming.
Animal animal = new Dog();
Now, when I try to call: buy(animal);
the compiler complains that there
is no method "buy" which accepts an Animal object.
So, my questions are:
1. Is there any way to do this without instanceof and downcasting?
2. If so, how?
3. If not, why not? The JVM has enough runtime information to
know exactly what type the object is. I thought that's
what polymorphism is all about.
4. Am I doing something obviously stupid here? I've thought
about it so much I'm just not sure now.
Any help greatly appreciated.