I need to be able to call the constructor of an inheriting class depending on what is input for the method newInstance(String kind)... my code currently looks like this:
public class Animal {
public String kind;
public String integument;
protected Animal(){
}
public Animal newInstance(String kind){
kind x = new kind();
return x;
}
So for instance, if the String put in was "owl", I want it to call the constructor in my previously created owl class and create a new owl instance. The owl class looks like:
public class Owl extends Bird{
public Owl(){
this.kind = "owl";
}
public void newOwl(){
}
@Override
public String sound(){
return "'Hoot'";
}
}
Right now I get an error that says, "class kind is not found" because it is looking for a class called kind, rather than waiting for an input and looking for a class called the same thing as the string input.
How can I rewrite this code so that the input in that method will look for a class by that name and create a new object of that type? Thanks!
Class.forName(kind).newInstance(), which does exactly what you've described. But that's probably not a very good solution to your problem. What problem are you actually trying to solve?switch(kind) { case "owl": return new Owl(); }Animal.newInstance()as a Factory Method. A little more detail would help us narrow down the wide range of possibilities here.newInstancemethod you show calls akindconstructor and returns its result as anAnimal. That looks definitely wrong. A complete example would help.switchbecomes the best way.