Originally Posted by
Junky
Casting to a Panda will not work. What happens if the factory method returns a Monkey object? Obviously it cannot be cast to a Panda. Since a parent class has no idea about what subclasses there are this is not possible. You might want to rethink your design.
Thanks Junky, and sorry if it was I who made you grumpy! :-)
I guess I expected that Java would instantiate a Panda, eg using the default no-arg constructor (which is provided) to allow the cast to happen. I also would have expected a run-time error where the cast is not up or down the class hierarchy (as in the cast from monkey to panda). But, I'm just showing my ignorance again i guess!
OK so I have a new approach, with a factory class that takes a generic:
public class AnimalFactory <T extends Animal> {
private Class<T> thisClass;
public AnimalFactory(Class<T> c) {
thisClass = c;
}
public T make() throws Exception {
final T animal;
animal = thisClass.newInstance();
return animal;
}
}
Then I can do something like
AnimalFactory<Panda> pandaFactory = new AnimalFactory<Panda>(Panda.class);
Panda p = pandaFactory.make();
Does that look like a more standard approach?
It works so far, but I find that I'll need to use some reflection if I want to actually do other things with the class I am making. Since java doesn't allow me to access methods or variables of "T" directly...