Originally posted by Mathew Kuruvilla:
Another question is:
What are the different ways in which polymorphism can be achieved in Java. I know that having the same method name with different signatures or parameter list is one way. Is there any other way that polymorphism can be achieved in Java.
Thanks.
Matthew
Strictly speaking, having the same method name with different signitures within a single inheritance tree is overloading, and has nothing to do with polymorphism.
Polymorphism is where the exact same message elicits different behavior from objects in the same inheritance tree. Simple example: the Dog and Cat classes both inherit a speak() method from the Pet class, and each overrides that method to provide its own behavior.
There are different ways this can play out:
The Pet class provides an implementation of the speak() method that can be overridden in the child classes, and each can implement it differently. The Pet class can be abstract, and provide implementations only for common behaviors, which probably would not include the speak() method. This forces the child classes to implement their own speak() behavior. Pet can be an interface that defines the signature for a speak() method, again forcing implementors to provide the behavior. In these scenarios, the program can cycle through an array of Pet objects, calling the speak() method on each one, and get the appropriate behavior.
Which one you choose depends on the problem space you are working in. In the case of my dogs and cats example, I would probably choose to have a Pet interface, and possibly an abstract Animal class. It would depend on how complex the behavior is, and how many common behaviors can be abstracted out of the concrete classes. The Pet interface could be used for something no more complex than to distinguish a feral cat from a house cat, even if they both have the exact same behaviors.
You can see how in some cases, interfaces, concrete and abstract classes map pretty well to a description of the real-world objects, classes and relationships.
I hope this is helpful, and more importantly, that I got it right! :roll:
[ July 09, 2003: Message edited by: Philip Shanks ]