1

What I am trying to do is most easily explained as such:

Animal animal = petStore.getRandomAnimal();

if(animal.isDog()){
    kennel.add(animal)
}

Obviously I can not do it this way since kennel.add() only accepts type Dog.

I have determined that the animal is a dog, but how do I let the compiler know this?

working in java.

  • 1
    This question has been marked as duplicate, but this question is not about instanceOf (although that was a handy thing to learn). This question was about casting. – Tom McSkimming Apr 27 '18 at 13:58

1 Answers1

2

Just cast the Animal Object to Dog class

Animal animal = petStore.getRandomAnimal();

if (animal instanceof Dog) {
    kennel.add((Dog) animal)
}
TheBakker
  • 2,852
  • 2
  • 28
  • 49