get data from subclass after casting to superclass

1.1k Views Asked by At

Hi guys I'm having this small problem. I have this:

public class Animal {
    //omitted
}

public class Dog extends Animal {
   private int speed;
}

Now that I have another class that generate an iterator and cast all of its object to the Animal one.

while(it.hasNext()) {
   Animal animal = (Animal) it.next();
}

However some of the objects are Dog and I dont know how to get the attribute "speed" from the subclass.

Sorry for asking this kind of question, I'm kind of new to Java. Thanks for concerning.

1

There are 1 best solutions below

0
On BEST ANSWER

Check if animal is a Dog, then cast it

if (animal instanceof Dog) {
    ((Dog)animal).getSpeed();
}