Polymorphism is made of two words poly and morphs. "Poly" means many and "morphs" means form. So polymorphism means many forms. The word 'Polymorphism' literally means 'a state of having many shapes'.
There are two types of Polymorphism in Java
- Compile time polymorphism (Static binding)
- Run time polymorphism (Dynamic Binding)
Method overloading is an example of static polymorphism, while method overriding is an example of dynamic polymorphism.
A common example of polymorphism is when a parent class reference is used to refer to a child class object.
Note: An object in Java that passes more than one IS-A tests is polymorphic in nature.
Compile Time (Static) Polymorphism
Method overloading is an example of static polymorphism. Method overloading means having several methods with same name but with different parameters or argument list.
Java decides which method to invoke by checking the argument list and this is done at compile time. Therefore it is known as compile time polymorphism or static polymorphism.
According to the parameters passed java invokes the right method. If the parameters doesn't match any of the method definition, it will show an error.
Run Time (Dynamic) Polymorphism
Method overriding is an example of dynamic polymorphism. Must check this section for detail. In method overriding a child class has same method as in parent class.
Lets understand how polymorphism is implemented. Consider the below example
In the above example, the reference type is
Shape and the object being referenced is
Circle. So, when show() method is called, Java waits until runtime to determine which object is actually being pointed to by the reference. Here the object is of
Circle class so the method of class
Circle is invoked. In the next case, the reference is still of
Shape class but now the object is also of
Shape class, therefore this time the method of parent class is invoked.
This is also known as Dynamic binding or Late binding because the decision to invoke method is taken at runtime.