3

A method eat() uses a parameter of type Food, while Food is a generic class:

class Food<T> {
    T type; 
    ...
}


class Human {
    public void eat Food(Food food) {
        // eat, eat, and eat, however it has nothing to do with T
    }
}

The question is, should I declare Food<?> instead of Food in eat's parameter? Are there any difference while the method eat doesn't care and use anything related with T?

deHaar
  • 17,687
  • 10
  • 38
  • 51
guo
  • 9,674
  • 9
  • 41
  • 79
  • 3
    Why are you using generics? – ernest_k Sep 03 '18 at 08:34
  • 1
    What are those `type`s of `Food`? – deHaar Sep 03 '18 at 08:36
  • 1
    Are generics really what you want here? Maybe try mkaing `Food` an interface, and use specific implementations if needed required. – Alex M Sep 03 '18 at 08:43
  • Maybe you currently don't care that `T` could be any type of object. All you need is the toString() or something like that. But it could be useful to establish a base FoodType (Interface). So, if you later do need assumptions that should be common to every FoodType, then those will be guaranteed to be in place. – Patrick Parker Sep 03 '18 at 08:50
  • The difference is that with `Food food` you can assign anything you like to `food.type`, e.g. a `String`, an `Integer`, a `Frobnitz`. If the value you pass the method as a parameter is, say a `Food`, that will (may) lead to a problem later (specifically, a `ClassCastException`). `Food> food` prevents this. Raw types: stay away. – Andy Turner Sep 03 '18 at 08:51

1 Answers1

0

If you use just Food, then you're using a raw type. The compiler will issue a warning, since it loses any information and cannot do any type checks on subsequent uses of this type. So if you don't care about T inside the method, use Food<?> and let the compiler know about this fact.

memo
  • 1,868
  • 11
  • 19