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
Answer to your question
Posted by Sharadha Eswar on August 28, 2000 at 5:05 PM
> 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.
ALl you need to do is implement dynamic polymorphism in your code
a. Create the buy function to be a virtual function ( in java abstract function )
b. in the derived class Dog and Cat implement the Buy functions accordingly . ( need not declare them virtual)
c. Now create the instance of dog as u described
Animal a = new DOG()
this function call will call the dog's bug functions.
What u are trying to imeplement in you code is dynamic polymorphism and you are using overloading which is wrong.
Overloading is to implement static polymorphism !.
Hope this helped.