|
Re: what are generic types used for?
|
Posted: Apr 24, 2008 9:36 PM
|
|
Generic type is used to create new parameterized type.
From your text, it is clear that you know value of, e.g. Generic List class, which can be later instantiated as List of Strings or ints or any other type. Note that all these 'lists' have common interface and that means, we can use polymorphisms to our advantage.
In you example, if you create Order<P, Q, R>, and later instantiate Order<TV,FRIDGE,WASHMACH>, you are limiting yourself. In this case, order can be of some TV,FRIDGE and/or WASHMACH only. What if, later (who knows future?), you want Mixer to be part of an order as well. Rather, it would make sense to create interface called IOrderItem and let a class implement it - so that it can be part of Order as Order will maintain maybe List<IOrderItem>.
Order composed of Items Item must implement IOrderItem
Also, in your case, addItem() will accept which type of object? You may have to overload this method with parameter types of P, Q, R etc.
All in all, in your case, you are tight-coupling Order as compile time with TV, Fridge and WashMach classes. So, your Order class will be less reusable as you cannot add Mixer in your order! Order should be agnostic to real type of order item.
Generic class are supposed to be instantiated with different types as argument(s). If you are always going to instantiate Order class with TV, Fridge and WashMach class, there is no point in taking pain to define generic class at all!
I hope this helps.
|
|