I have an abstract class Animal
, with two extending classes, Dog
and Cat
.
public abstract class Animal {
...
}
public class Dog extends Animal {
...
}
public class Cat extends Animal {
...
}
In another class, I have an ArrayList<Animal> animals
that contains instances of both Cat
and Dog
.
In the class with the ArrayList<Animal>
, I want to be able to overload a method doSomething()
with either Dog d
or Cat c
as the parameters, but still be able to call them from the ArrayList of Animals. As follows:
public void aMethod(){
ArrayList<Animals> animals = getTheAnimals();
for (Animal a : animals){
doSomething(a);
}
}
public void doSomething(Dog a){
//a is an object of type dog
}
public void doSomething(Cat a){
//a is an object of type cat
}
Essentially, each method is acting as a 'selector' for which type
of animal is being received by the method.
When trying as above, I get the following compilation error:
error: no suitable method found for doSomething(Animal)
I know I could use something like instanceOf
or a.getClass().equals(type)
, but I have read that this is bad practice.
This question differs slightly from this other question, as I want two separate methods, each with a different parameter.
EDIT: I am going to avoid using the Visitor Pattern as I don't think it really fits well into my actual implementation. Will move the doSomething() method into each class, and refactor to ensure this makes logical sense (each class performing actions that it should be responsible for). Thanks.