I have three classes Dog.java, Cat.java and Monkey.java all implementing interface Animal.java. I then have DogManager.java, CatManager.java and MonkeyManager.java each having the following method and returning a Dog, Cat, Monkey instance respectively:
public Animal getAnimal();
Finally I have a factory class that takes an animal name and returns an appropriate animal instance.
public Animal getAnimal(String name);
This all works fine, till I have to use the Animal object returned by the factory class to my controller class where I expect to call the bark() method exposed by Dog.java when I get the Dog instance from the factory but I don't have that method available since my factory returns Animal type which does not have bark().
So I was thinking of trying passing a class object to the getAnimal() in my factory class:
public <T> T getAnimal(String name, Class<T implements Animal> clazz);
However, this requires I know the class association for each animal name. I was trying the following:
IManager.java
Class<?> getClassName();
String getName();
DogManager.java
public Class<?> getClassName(){
return Dog.class;
}
public String getName(){
return "Dog";
}
public Dog getName(){
return new Dog();
}
CatManager.java
Class<?> getClassName(){
return Cat.class;
}
public String getName(){
return "Cat";
}
And then in my factory call:
IManager manager = getManager(); //Here I will get one of the Cat/Dog/Monkey managers based on name
factory.getAnimal(name, manager.getClassName()); //Compilation fails here
But this does not work, since getAnimal takes Class and manager.getClassName() is returning Class.
Any idea how can I make this work?
makeSound()inAnimal, but this is basically a lot of code for absolutely no benefits.