Polymorphism in Java | Java Tutorial
Polymorphism allows us to perform a task in multiple ways. Let’s break the word Polymorphism and see it, ‘Poly’ means ‘Many’ and ‘Morphos’ means ‘Shapes’.
Let’s see an example. Assume we have four students and we asked them to draw a shape. All the four may draw different shapes like Circle, Triangle, and Rectangle.
We will see detailed explanation with some example programs about Polymorphism in the post related to Polymorphism.
There are two types of Polymorphism in Java
1. Compile time polymorphism (Static binding) – Method overloading
2. Runtime polymorphism (Dynamic binding) – Method overriding
We can perform polymorphism by ‘Method Overloading’ and ‘Method Overriding’
I recommend you to go through the following posts.
Method Overloading: (Static Polymorphism/Compile time polymorphism)
Method Overriding: (Dynamic Polymorphism/Run time polymorphism)
Let’s see some practical examples of both compile time polymorphism and run time polymorphism.
Compile Time Polymorphism:
ackage polymorphismCompileTime; public class CompileTimePolymorphismClass { void myMethod (int a){ System.out.println("value of a is " + a); } void myMethod (int a, int b){ System.out.println("value of a is " + a + " and value of b is " + b); } void myMethod (String a){ System.out.println(a); } public static void main (String [] args){ CompileTimePolymorphismClass obj = new CompileTimePolymorphismClass(); obj.myMethod(10); obj.myMethod(10, 20); obj.myMethod("I am a String"); } }
Output:
value of a is 10 value of a is 10 and value of b is 20 I am a String
Run Time Polymorphism:
package polymorphismRunTime; public class MethodOverridingParentClass { public void myMethod(){ System.out.println("I am a method from Parent Class"); } }
package polymorphismRunTime; public class MethodOverridingChildClass extends MethodOverridingParentClass{ public void myMethod(){ System.out.println("I am a method from Child Class"); } public static void main(String [] args){ MethodOverridingParentClass obj = new MethodOverridingChildClass(); // It calls the child class method myMethod() obj.myMethod(); } }
Output:
I am a method from Child Class
Must Read: Java Tutorial