Lets say I have a class named Dog which is a subclass of Animal
I have a method that needs to create an instance of a specific subclass of animal based on a string parameter
public void createAnimalType(String animalType) {
Class clazz = Class.forName(animalType);
//Check if animalType equals Dog, or Cat, or Fox, etc
// Example
Dog dog = (Dog) clazz.newInstance();
...
Is there a way to crate an instance of itself (Dog, Cat, etc, Not of type Animal) without using an explicit cast to the Subclass (Dog)in this case?
I may be missing a finer point of polymorphism (as in why do I want to do that . . should be casting it to Object or Anmial :-) )
Thanks for helping me get smart on this.
If there is a no-args contructor, you can use
getClass().newInstance()
.getClass()
when used in a superclass will give you the actual class ofthis
, for exampleDog
in your example.Your whole method would become: