What is Polymorphism in Java?
Polymorphism refers to "having many forms" or more than one form. In OOPs, it is the ability to create a variable, function or object which has many form. In the Java Programming Language, two types of Polymorphism are there:
1. Compile Time Polymorphism
Also known as Early Binding or Static Binding. In this case, the compiler identifies which polymorphic form is to be executed at compile time. Method overloading and Operator overloading are good examples of Compile Time Polymorphism. The following written program demonstrates Compile Time Polymorphism.
Method Overloading
When a class contains methods of the same name but of a different number of parameters, is called Method Overloading.
Code
- public class MethodOverloading {
- public static void main(String[] args) {
- MyClass obj = new MyClass();
- int sum = obj.Add(4, 5);
- System.out.println(sum);
- sum = obj.Add(4, 5, 7);
- System.out.println(sum);
- sum = obj.Add(4, 5, 7, 9);
- System.out.println(sum);
- }
- }
- class MyClass {
- public int Add(int a, int b) {
- return a + b;
- }
- public int Add(int a, int b, int c) {
- return a + b + c;
- }
- public int Add(int a, int b, int c, int d) {
- return a + b + c + d;
- }
- }
Output
2. Runtime Polymorphism
Also known as Late Binding or Virtual Method Invocation or Dynamic Binding. In Runtime Polymorphism, the compiler identifies which polymorphic form is to be executed at runtime but not in compile-time, is called Runtime Polymorphism. Method overriding is a well-known example of Runtime Polymorphism.
Method Overriding
Method Overriding takes place if Inheritance exists and a superclass and subclass have the method of the same signature. Signature refers to access specifier, return type, name, parameters(number, type & order) & throws clause of the method. Then, the method of the subclass overrides the method of the superclass. As demonstrated in the following written program.
Code
- public class MethodOverriding {
- public static void main(String[] args) {
- ClassB obj = new ClassB();
- obj.Display(10, 15);
- }
- }
- class ClassA {
- public void Display(int a, int b) {
- a += 5;
- b += 7;
- System.out.println("Sum is " + (a + b));
- }
- }
- class ClassB extends ClassA {
- public void Display(int a, int b) {
- System.out.println("Sum is " + (a + b));
- }
- }


Join the conversation! Your thoughts help the community grow.