Assume I have an inheritance structure like this:
abstract class Fruit {}
class Apple extends Fruit {}
class Orange extends Fruit {}
In my application, I have a method that takes a "type" argument like this:
public Fruit getFruit(String type) {
if (type.equals("Apple")) {
return new Apple();
} else if (type.equals("Orange") {
return new Orange();
} else {
return null;
}
}
My question is, how can I can initialize the fruit instance generically here so that I don't have go through this if/else chain? Is there such a way that I could have a Fruit() constructor that takes an argument which specifies which subclass to initialize? Something like "new Fruit("Apple")".
Apologies for the oversimplification, but this is the crux of my issue. I should mention that Fruit and it's children is actually a TABLE_PER_CLASS JPA Inheritance strategy and the type comes from a column in a FruitPicker entity. If it helps, each fruit has a reference to the FruitPicker that generated it.