Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic class initialization

This is my class:

public class FoodSet<T extends ConcreteFood>{
    public List<T> food = new ArrayList<T>();
    public FoodSet()
    {
        /*
        *  FoodType is an enum containing food types e.g: rice, pork, beef ...
        */
        for(FoodType foodType : FoodType.values())
        {  
            /*
            * 1(*)
            * /
            food.add( (T)new ConcreteFood(foodType,0) ) 
        }       
    }
}

And in 1(*) is the problem, how to init this list, with 'T' type ? Now I init it with ConcreteFood, giving as argument foodType and amount, but my goal is to init this list with T that extends ConcreteFood. Every subclass of ConcreteFood has access to foodType and food count. I just would to init this list with apropriate ConcreteFood subclass and init each ConcreteFood object with foodType and count = 0. How should I do it ?

like image 640
friko Avatar asked May 21 '26 22:05

friko


2 Answers

This isn't what you want. You need a factory class to create instances of ConcreteFood for you.

public class FoodFactory {
    private static final FoodFactory INSTANCE = new FoodFactory();

    private FoodFactory() {}

    public static FoodFactory getInstance() { return INSTANCE; }

    public Food create(FoodType type) {
       // Put the type checks here 
    }
}

I don't care for your naming much. "ConcreteFood"? Doesn't sound appetizing. Why not FoodCategory?

like image 167
duffymo Avatar answered May 23 '26 11:05

duffymo


You could use your FoodType enum as a factory:

public static class ConcreteFood {
}

public static class Bacon extends ConcreteFood {
};

public static class SavoyCabbage extends ConcreteFood {
};

enum FoodType {
  Pork {
    @Override
    public ConcreteFood makeNew() {
      return new Bacon();
    }
  },
  Cabbage {
    @Override
    public ConcreteFood makeNew() {
      return new SavoyCabbage();
    }
  };

  public abstract ConcreteFood makeNew();
}

public static class FoodSet {
  public List<ConcreteFood> food = new ArrayList<ConcreteFood>();

  public FoodSet() {
    /*
     *  FoodType is an enum containing food types e.g: rice, pork, beef ...
     */
    for (FoodType foodType : FoodType.values()) {
      /*
       * 1(*)
       */
      //food.add((T) new ConcreteFood(foodType, 0)) 
      food.add(foodType.makeNew());
    }
  }
}
like image 42
OldCurmudgeon Avatar answered May 23 '26 11:05

OldCurmudgeon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!