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.
Instead of iterating in your client method and calling doSomething(), keep doSomething() as a method in your abstract class, that way you can change the way you want in Cat or Dog.
public void aMethod(){
ArrayList<Animals> animals = getTheAnimals();
for (Animal a : animals){
a.doSomething();
}
}
abstract Animal {
doSomething();
}
Dog extends Animal {
doSomething() {
//Dog stuff
}
}
Cat extends Animal {
doSomething() {
//cat stuff
}
}
Move method into Abstract class so each implementation has to make its own version of the method.
public abstract class Animal {
public abstract void doSomething();
}
public class Dog extends Animal {
public void doSomething(){
System.out.println("Bark");
}
}
public class Cat extends Animal {
public void doSomething(){
System.out.println("Meow");
}
}
Then in the other Class you mentioned above you can do the following:
public void vocalize(){
List<Animal> animals = getTheAnimals();
for (Animal animal : animals){
animal.doSomething();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With