This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Well, Serializable, Set, and Collection are all interfaces. If you look in the API at the HashSet class, for example, one of the things that you will see in the main definition of HashSet is that it implements ALL of Serializable, Set, and Collection interfaces. So, in your example, hs is a reference of type Set but it is pointing to an object of type HashSet.
Just to try a few points, you would not expect to serialize a Set because a Set can not be instantiated (you can not do Set hs = new Set(); ). So set doesn't really need to implement Serializable. As long as the underlying classes implement Serializable then the objects that you instantiate as your collections will be serializable.
SCJP - 86% - June 11, 2009
Joined: Nov 12, 2008
Originally posted by Bob Ruth: you would not expect to serialize a Set because a Set can not be instantiated (you can not do Set hs = new Set(); ). So set doesn't really need to implement Serializable.
You are correct, because Set cannot be instantiated, while it is an interface.
However, is it a reason for not extending Serializable interface? Then tell me, why those List, Set, and Map interfaces are available?
The answer is, those interfaces are provided for keep them as common references. For an example, as I know, we should use either List, Set, or Map, instead of ArrayList, HashSet, TreeMap,... as references in a Web Service End point. Because List, Set, Map and some other interfaces are the common types in collections. In this case, using an interface-reference is much more better than using a class-reference for collection types.
is better than,
Now the same problem occurred again. How can we pass hs1 object to a Serializable reference, without doing an explicit cast? My real question is, why Sun didn't extend Serializable interface for Set, List, Map and Collection interfaces? :roll:
Let me guess: someday somebody might want to write an implementation of Set which was not serializable. Seems to me that is not a wrong thing to do. Now they can do it. If Set implemented Serializable then they could not do it.