So if I have a method that takes a Shape argument and Shape is a base class, you can give that method any class that extends Shape and the method can call Shape methods on it.
If the method takes IShape argument and IShape is an interface, you can give that method any class that implements IShape. Now, if Shape implements IShape, you can pass either a derived class or something that implements IShape. You see this sometimes in the JDK with "DefaultSomething" classes.
Hope that helps!
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.
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:
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 ]