Hi I'm wondering if there is a simple solution to my problem,
I have an ArrayList
:
ArrayList <Animal> animalList = new ArrayList<Animal>();
/* I add some objects from subclasses of Animal */
animalList.add(new Reptile());
animalList.add(new Bird());
animalList.add(new Amphibian());
They all implement a method move()
- The Bird
flies when move()
is called.
I know I can access common methods and properties of the super class by using this
public void feed(Integer animalIndex) {
Animal aAnimal = (Animal) this.animalList.get(animalIndex);
aAnimal.eat();
}
That's fine - but now I would like to access the move()
method the subclass Bird
has.
I could do this by casting the Animal
as a Bird
:
Bird aBird = (Bird) this.animalList.get(animalIndex);
aBird.move();
In my situation I don't want to do this, as it will mean I have 3 different sets of the above code one for each subtype of Animal
.
It seems a bit redundant, is there a better way?
There really isn't a nice way to do this from the superclass, since the behavior of each subclass will be different.
To ensure that you're actually calling the appropriate
move
method, changeAnimal
from a superclass to an interface. Then when you call themove
method, you'll be able to ensure that you're calling the appropriate move method for the object you want.If you're looking to preserve common fields, then you can define an abstract class
AnimalBase
, and require all animals to build off of that, but each implementation will need to implement theAnimal
interface.Example:
You dont need to do any casting. The overridden method should get called [simple polymorphism]
Above code should call bird method if object is of bird, isn't it?
And casting is not a solution , how will you decide which object to cast? You will have to use instanceOf.
In your case,the following could work,but time complexity is O(n):