Polymorphism is another pillar of Object Oriented programming. It is form of software reusability where different classes related to each other either through inheritance or implementation behave differently to the same method call.
In simple words, polymorphism means multiple forms. One method can be written in multiple ways and appropriate method will be called out of those multiple methods depending up on conditions at run time.
Polymorphic behavior can be achieved by method overloding, method orverriding and dynamic binding.
Let's understand the polymorphic behavior of the class using example:
As you can see above, I have created a class Human.java with only one method named greetingMessage which takes one parameter (name) of type String and return type void. This method prints greeting message to the console without title like Mr. or Mrs.
Now, I have create another class Man.java that extends Human.java. This class overrides the greetingMessage method of its super class Human.java and prints the message to the console with title Mr.
Now, I have create another class Woman.java that extends Human.java. This class also overrides the greetingMessage method of its super class Human.java and prints the message to the console with title Mrs.
Now, I have created the implementation class to demonstrate the polymorphic behavior. I have created 3 instance of 3 class with type of Super class Human.java
1st instance is of super class Human.java and its type is also of super class Human.java
2nd instance is of class Man.java and its type is of super class Human.java
3rd instance is of class Woman.java and its type is of super class Human.java
All these instances are calling the same method greetingMessage. However based on type of instance, JVM decides which method to invoke.
As you can see in the console, 1st instance call the method in super class itself and it prints name without title. Similar way 2nd instance call the method in subclass Man.java and it prints name with Mr. title and 3rd instance call the method in subclass Woman.jaba and it prints name with Mrs. as title.
Hope you have enjoyed the topic. If you have any question or comments, please provide it in the box displayed below with your name and comments/questions.