0

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.

daniel9x
  • 755
  • 2
  • 11
  • 28
  • I don't see anything about a superclass constructor. – shmosel Apr 25 '17 at 01:35
  • 1
    You can use lambdas nowadays for this too. `Fruit getFruit(Supplier s) { return s.get(); }` and `getFruit(Apple::new)`. – Radiodef Apr 25 '17 at 01:36
  • My question is how to initialize a specific subclass instance of a given supertype by simply passing in the argument from the method. The solutions to the "duplicate" don't really address inheritance but seem rather reflection-based. I was hoping there might be a simpler solution. – daniel9x Apr 25 '17 at 01:45
  • How about using an **enum** for `type` with the generic class as property? Something like `APPLE(Apple.class), ORANGE(Orange.class);` then create a method containing `return this.fruitClass.newInstance();`. – juvenislux Apr 25 '17 at 02:34

0 Answers0