Re: Searching a motivating example for upcasts
On 12/19/2010 03:03 AM, markspace wrote:
On 12/18/2010 10:17 PM, Abu Yahya wrote:
What is better, using List with a type parameter (like List<String>) or
List without the type parameter? List<String> seems right to me, but
isn't fully "flexible".
What do you mean by "flexible" in quotes?
The point of generics declarations is similar to the point of, say, method
declarations or any other type declaration - you lock down the type by the
declaration. If you don't need a specific type, you lock down to a more
general type.
You should always lock down the type of your collection or other generic
class. Never use raw types. (Hacks that violate that rule notwithstanding.
They're hacks, and they're violations of that rule. It doesn't invalidate a
rule that there are exceptions. That's pre-emptive logic for all you
nitpickers who will rush to explain all the exceptions to the rule. Pointing
out exceptions is a form of acknowledgment of the rule, which is itself valid.)
I gave the example without a type parameter because Stefan was talking about
introducing students to polymorphism and inheritance. He wanted a "motivating
example" and there's lots of examples without the type parameters because
generics are relatively new in Java.
In new code, you should always use the type parameter. If you want
flexibility, use List<Object>.
Or, for cases where it's the right type declaration, 'List <?>' or 'List <?
extends DesiredSupertype>'.
The trick is to do a complete type analysis and capture the results in your
generics and interface declarations. Then the type declarations document your
analysis and the compiler enforces it.
--
Lew
Ceci n'est pas une pipe.