The Artima Developer Community
Sponsored Link

Legacy Design Forum
Designing with Runtime Class Information

Advertisement

Advertisement

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 Artima Forums.

Message:

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
> examples:

> 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.

> Cheers,

> Chris


ALl you need to do is implement dynamic polymorphism in your code
Steps involved
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()
a.Buy()
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.




Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us