title: How to create a new type of object based on a String?
body: <p>first time posting here. Just starting to learn Java and coding in general, so please be patient with me!</p>
  
  <p>So here I have a few classes. A Fruit class, with 2 subclasses - Orange and Watermelon.</p>
  
  <pre><code>public class Fruit {
      String name;
      String size;
  
      public Fruit() {
          this.name = "Fruit";
          this.size = "";
      }
  
      public String getName() {
          return this.name;
      }
  
      public String getSize() {
          return this.size;
      }
  }
  
  class Orange extends Fruit {
      public Orange() {
          this.name = "Orange";
          this.size = "Small";
      }
  }
  
  class Watermelon extends Fruit {
      public Watermelon() {
          this.name = "Watermelon";
          this.size = "Large";
      }
  }
  </code></pre>
  
  <p>I also have a Crate class, that I want to store Fruit Objects. However, I want it to store a particular object, based on what String is passed to the constructor.</p>
  
  <pre><code>public class Crate {
      Fruit f = new Fruit();
  
      public Crate(String fruitType) {
          if (fruitType == "Orange") {
              f = (Orange)f;
          } else {
              f = (Watermelon)f;
          }
      }
  
      public String getFruitName() {
          String s = f.getName();
          return s;
      }
  }
  </code></pre>
  
  <p>Trying to downcast like this gives me an error. My question is how could I accomplish adding a certain Fruit subclass to the Crate object based on what is passed to the constructor?</p>
  
  <p>EDIT: thank you everyone for the advice. Made the changes suggested and it works great! </p>