Polymorphism in Java

What is polymorphism in Java?

Polymorphism in Java is the principle by which an object can have multiple forms but each form conforms to a contract. Polymorphism can be thought of as a direct consequence of abstraction. In the earlier section, we say how abstraction separates method definition from its implementation. When we have two different implementations of that abstraction we call it polymorphism (poly in the Greek means “many” and morph means one of a different form of a species). To see what it means, let’s look at an example:

The example does not try to teach you English but does demonstrate the concept that an Animal is an abstract concept and the cat or dog is the actual animal implementation. Dog and Cat are the different forms of animal. It might not be intuitive at what this all means, but let’s look at a java example to explain this concept.

Animal is an abstract class and is extended by the Dog and Cat class. Both the Dog and Cat implement the getDiet() method. The interesting part is how the client uses this:

The example looks interesting, since we have created a Cat and Dog and assigned them to the Animal type (class). However, when we call the getDiet method, the appropriate method gets called. The reference type ‘Animal’ has multiple forms now – Cat and Dog and this explains polymorphism quite clearly.

Leave a Reply

Your email address will not be published. Required fields are marked *