#Is Downcasting a superclass object as a subclass object bad in this case? How could you improve it?

6 messages · Page 1 of 1 (latest)

stable robin
#
if (animal instanceof Herbivore)
            {
                this.herbivores.add((Herbivore) animal);
            }
            else if (animal instanceof Carnivore)
            {
                this.carnivores.add((Carnivore) animal);
            }

In the code snippet above, the animal variable is an Animal object, which is the superclass for subclasses, Herbivore and Carnivore. Here, I want to check if the animal is a subclass or not, and if so, add it to the respective ArrayList of Carnivores or Herbivores. Is this bad practice; I heard that downcasting is always bad. If so, what's a better solution?

bronze hatchBOT
#

This post has been reserved for your question.

Hey @stable robin! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

candid sierra
#

But assuming animal is a function argument, you can overload

#

And if you casted it up somewhere, the original surely exists