posted 13 years ago
I always use the most general type possible (within reason). If you can't foresee needing the special behaviour of a specific class, then simply use a more general reference.
This is because general types are easier to use, and if you want to change the behaviour of your class, it's easier to do so without having to change other code.
Here is an example:
In this case I used Animal as the type for pet. I could have decided to go with Tiger, but now it's easier for me to change what kind of animal I want to play with, without having to change the declaration.
For instance, I can decide that Tigers are too dangerous to play with, then I just replace
with
Just do it within reason. I think the Collections API is a good example. I always use a general type like List or Set or Map, instead of ArrayList, TreeSet or LinkedHashMap. In most cases I could use the even more general type Collection, or even Iterable, but I think that a class like List conveys what I want to achieve much better.