Reputation: 17258
I have some work code whereby using generics has started to make the code look more confusing than it should.
Is it possible that I do away with generics and use interfaces for member types, constructor types, method parameter types and method return types?
What would generic provide, that the above using interfaces would not? I understand generics does compile-time checking when retrieving elements (to stop wrong casting- like in the old days), but wouldnt the compiler detect if I tried inserting types which were not a sub type of the interface required?
Upvotes: 1
Views: 1257
Reputation: 13169
Interfaces announce to all how a class must behave at all times. On the other hand type parameters (generics) let a client decide how the class should behave in a particular instance.
Type parameters make a class generic by allowing it to process a range of object types with just the one set of methods and fields, and provide compile-time checking to make sure that only the specified type is being used by each particular instance.
If you try to offer such flexibility using interfaces, you will have to write multiple versions of the same methods and classes, where each version does basically the same thing but with a different explicit type. This will be boring (which leads to cut-and-paste errors) and bulky, without adding anything at all.
The generic syntax is a bit funky looking, but you quickly get used to it, so don't let the initial ugliness of the angle brackets stop you taking advantage of a powerful feature.
Upvotes: 0
Reputation: 33544
Generics makes the Collections more type safe.
If there is an extensive use of Collections in your working code, i will prefer sticking with the generics.
And moreover as the infamous proverb states, "program in Interface, not in implementation", Interface is moreover for flexibility than type safety.
Generics are also used for Class, method , interfaces, variables, constructor. etc....
See these link for more details :
http://en.wikipedia.org/wiki/Generics_in_Java
http://www.oracle.com/technetwork/articles/javase/generics-136597.html
Upvotes: 4