Possible Duplicate:
Try to describe polymorphism as easy as you can
I’ve never been able to fully comprehend what polymorphism is. Can someone explain, perhaps with use of an example, what it is and how it works? Just the basics.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Perhaps it’s easiest to start with a non-computer analogy.
Consider if you told somebody to “Go to the store and buy some of your favorite food for supper.”
If you said this to a 14 year-old son, he’d probably ride his bike to the store, have to pay cash for the food, and you’d be having pizza for supper.
If you said it to your wife, she’d probably drive to the store, use a card to pay for the food, and you might be eating chicken Cordon Bleu with Chardonnay instead.
In a program, things work out a bit the same way: you specify something at a relatively abstract level (go to the store and get supper). Each object provides its own concrete implementation of how to implement that, and in many cases provides for some variation in exactly what it’s going to do (e.g., like the differences in favorite foods above).
Of course, when you’re programming, most of that requires a specification that’s a lot more detailed and unambiguous. The general idea remains the same though. For the scenario above, you might have a
personbase class (or interface) that defined methods likego to storeandselect favorite foodandpay for purchase. You’d then have implementations of that likeadultandteenager, each of which defined its own method of going to the store, selecting favorite food, and paying for a purchase. Those methods would be polymorphic, because each implementation would have its own way of carrying out the higher-level command you gave.