Lew said:
What do you mean, "about all the reason to do so"? There are a gazillion
reasons to do so.
That's why I "stepped back": to leave the explanation of those gazillions
of reasons to those who actually find them worth the time to post them...
Here's some scenarios (as a starting point for your gazillion of reasons):
- you find out that you *do* need the sub-class's extra methods, then
you have to change the declaration to use the subclass.
- you need the extra methods, but don't change the var's type, but
rather use a downcast ("I know it's a HashMap!") on the spot...
Bad Bad Bad ! (btw., the "you" isn't meant personally)
Of course you wouldn't ever do that, but a newbie indoctrinated
to always use the most abstract class for local vars, might do it.
- you don't need the subclass's extra methods, and have to change the
implementation (e.g. HashMap -> TreeMap). If you used Map before,
there is just one change, if you used HashMap before, then you also
change the variable to either Map or TreeMap now - the second change
is in the same line most of the times, or at least in the same
method, anyway. And the compiler will yell if you forget it.
So not that big a deal, really.
To me, any extra thinking effort invested into finding the top-most
class/interface to use for a local(!) variable is just like premature
optimization.
Anyway, with Collections it's much less likely to ever need a specific
implementation's method than e.g. with the *Stream-family. Thus, using
List and Map wouldn't count as "extra thinking effort" for me.