Option 1 is not possible in Java, so it's easy to throw that out. Polymorphism really means multiple implementations of behavior. So, if you are working with something that implements the List interface and you call an add(object) method, that may add object to an internal array, or it could create a new node and add it to the end of a linked list. So that's why 3 is correct: ArrayList and LinkedList both implement List. Now if ArrayList implements List, RandomAccess, and Serializable, that shows it has more behavior than just the List interface, but it's not in itself an example of polymorphism.
Joined: Oct 04, 2011
Thanks for your response Greg. It was a good example. Let's examine one more example. TreeMap(class) implements SortedMap(interface) and the SortedMap extends Map (interface). Shouldn't the TreeMap is indirectly implementing multiple interfaces ? The TreeMap.putAll() method accepts the Map and SortedMap objects and thus achieves the polymorphism. Let me know, your thoughts. Thanks
Remember, I said one class implementing multiple interfaces is not an example of polymorphism. HashMap and TreeMap implementing the Map interface in different ways is polymorphism. If you are working with a Map, you don't have to decide which method to call. The Java runtime will look at the instance you are using and decide which method to call. That is, it will bind the call to the correct implementation.
A method like TreeMap.putAll() accepting different types could be an example of overloading, but not polymorphism. You might have two different implementations of the method, but the binding will be done at compile time.
Polymorphism comes into play when the JVM needs to sort out which implementation to execute when calling a certain method. If you have a reference of type Map, on which a method putAll is called, then the process of deciding where the implementation is, that's polymorphism. The implementation might be in TreeMap or in HashMap (or in any other class implementing the Map interface), depending on the type of object that the Map reference points to.
TreeMap implements multiple interfaces, but that's not the point and not necessary to have polymorphism.
SCJP 1.4 -- SCJD Java 2 -- OCM JEA 5
Joined: Oct 04, 2011
Greg and Paul : Thanks for your response. I was under impression that "one class implementing many interfaces" is one of the polymorphism characteristic. Your explanation, helped me to understand the concept clearly.