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.
public abstract class Animal { public abstract String getDiet(); } public class Dog extends Animal { @Override public String getDiet() { return "Dog Diet"; } } public class Cat extends Animal { @Override public String getDiet() { return "Cat Diet"; } }
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:
public class Client { public static void main(String[] args) { Animal cat = new Cat(); Animal dog = new Dog(); System.out.println(cat.getDiet()); // print "Cat Diet" System.out.println(dog.getDiet()); // print "Dog Diet" } }
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.