What is polymorphism? Explain with an example?

by jack| Views: 1631

What is polymorphism? Explain with an example?



Tags:  Oops Interview

Answers (1)
 
kethlin Said..

Polymorphism refers to the ability to assume different forms. In OOP, it indicates a language’s ability to handle objects differently based on their runtime type. When objects communicate with one another, we say that they send and receive messages.

An example of polymorphism can be demonstrated with geometric shapes. Suppose we have a Triangle, a Square, and a Circle. Each class is a Shape and each has a method named Draw that is responsible for rendering the Shape to the screen. With polymorphism, you can write a method that takes a Shape object or an array of Shape objects as a parameter (as opposed to a specific kind of Shape). We can pass Triangles, Circles, and Squares to these methods without any problems, because referring to a class through its parent is perfectly legal. In this instance, the receiver is only aware that it is getting a Shape that has a method named Draw, but it is ignorant of the specific kind of Shape. If the Shape were a Triangle, then Triangle’s version of Draw would be called. If it were a Square, then Square’s version would be called, and so on.

Advantage of polymorphism is that the sender of a message doesn’t need to know which class the receiver is a member of. It can be any arbitrary class. The sending object only needs to be aware that the receiving object can perform a particular behavior.



Register or Login to Post Your Opinion/Answer