![]() ![]() The method willl work regardless of you passing a HashMap or a LinkedHashMap to it, as long it's a subclass of Map. Take for example a method that accepts a Map as an argument. That makes both the appliance and the socket more useful. The same reason electric apliances makers built their products with electrical plugs instead of simply peeled out cables, and houses come with wall sockets instead of peel out cables sticking out of the wall.īy using standard plugs instead, they allow to plug the same apliances in any compatible plug around the house.įrom the point of view of the wall socket, it doesn't matter whether you plug a TV set or a stereo. Rather all methods in Dog or Cat should override methods in Animal and it will save you trouble in the long run. If you're dealing with Dog and Cat which derive from Animal, in order to make best use of inheritance, you should generally avoid having methods specific to Dog or Cat. However best practice still dictates that if it isn't important, you shouldn't use specific implementations. That said, could you override SortedMap and pass an unsorted one? Yes, of course, however expect bad things to happen as a result. ![]() This obliges the caller to necessarily pass a certain type of implementation of Map and strongly hints that order is important. If you need a map when order is important, then you can require a TreeMap or a LinkedHashMap to be passed, or better still SortedMap which doesn't specify a specific implementation. ![]() It should be said that there are exceptions to this when implementation is relevant. So as a general rule, you're supposed to handle its interface rather than the actual implementation and avoid the pain and suffering which might result in having to change all method signatures using HashMap when you decide you need to use LinkedHashMap instead. The reason is that the implementation of these interfaces is usually not relevant when handling them, therefore if you oblige the caller to pass a HashMap to a method, then you're essentially obliging which implementation to use. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |