Table of Contents
In this tutorial, we will see about Polymorphism in java.
Polymorphism in java is one of core Object oriented programming concepts with Abstraction, encapsulation, and inheritance.
Polymorphism
means one name many forms. In Java, polymorphism can be achieved by method overloading and method overriding.
There are two types of polymorphism in java.
- Compile time polymorphism.
- Run time polymorphism.
Compile time Polymorphism
Compile time Polymorphism
is nothing but method overloading in java. You can define various methods with same name but different method arguments. You can read more about method overloading.
Let’s understand with the help of example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package org.arpit.java2blog; public class MethodOverloadingExample { public void method1(int a) { System.out.println("Integer: "+a); } public void method1(double b) { System.out.println("Double "+b); } public void method1(int a, int b) { System.out.println("Integer a and b:"+a+" "+b); } public static void main(String args[]) { MethodOverloadingExample moe=new MethodOverloadingExample(); moe.method1(20); moe.method1(30.0); moe.method1(20, 30); } } |
When you run above program, you will get below output:
Double 30.0
Integer a and b:20 30
As you can see here, we have used same method name but different method arguments.The compiler will call appropriate method based on best-matched arguments.
Runtime Polymorphism
Runtime Polymorphism
is nothing but method overriding in java.If subclass is having same method as base class then it is known as method overriding Or in another word, If subclass provides specific implementation to any method which is present in its one of parents classes then it is known as method overriding
.
Let’s say you have parent class as Shape
and child class as Rectangle
and circle
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
package org.arpit.java2blog; public class Shape { public void draw() { System.out.println("Drawing Shape"); } public static void main(String[] args) { Shape s=new Rectangle(); s.draw(); s=new Circle(); s.draw(); } } class Rectangle extends Shape { public void draw() { System.out.println("Drawing Rectangle"); } } class Circle extends Shape { public void draw() { System.out.println("Drawing Circle"); } } |
When you run above program, you will get below output:
Drawing Circle
Please note that we are assigning child object to parent object here.
1 2 3 |
Shape s=new Rectangle(); |
As you can see we have overridden draw methods in child class Rectangle and Circle.JVM decides at runtime which method it needs to call depending on the object assignment. That’s why this is known as Run time polymorphism
.
That’s all about Polymorphism in java.