Polymorphism
Polymorphism
The word polymorphism is derived from the Greek words poly(meaning many), and morph(meaning form). Thus, polymorphism is the ability of an object to take more than one form.
Polymorphism is of two types:
- Compile time polymorphism
- Run time polymorphism
i. Compile-time polymorphism:
Java doesn’t support operator overloading and hence compile-time polymorphism is not possible in java.
But we can overload multiple functions with same name and different parameters or different type of parameters.
Example:
Output:
Here we have defined three methods with same name, but the parameters passed inside each differ by either the data type or the number of arguments passed. And we get output from each of these methods based on the input provided.
ii. Run-time polymorphism:
Run-time polymorphism or dynamic method dispatch involves overriding a method at run-time instead of compile-time.
Example:
Output:
Child classes have overridden the method of attribute parent class. Hence, when we create object of child class, then the method inside the child class is executed because it has more priority.