Compile time Polymorphism

Compile timePolymorphism 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

packageorg.arpit.java2blog;

publicclassMethodOverloadingExample{

publicvoidmethod1(inta)

{

System.out.println("Integer: "+a);

}

publicvoidmethod1(doubleb)

{

System.out.println("Double "+b);

}

publicvoidmethod1(inta,intb)

{

System.out.println("Integer a and b:"+a+" "+b);

}

publicstaticvoidmain(Stringargs[])

{

MethodOverloadingExample moe=newMethodOverloadingExample();

moe.method1(20);

moe.method1(30.0);

moe.method1(20,30);

}

}

When you run above program, you will get below output:

Integer: 20
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

packageorg.arpit.java2blog;

publicclassShape{

publicvoiddraw()

{

System.out.println("Drawing Shape");

}

publicstaticvoidmain(String[]args){

Shapes=newRectangle();

s.draw();

s=newCircle();

s.draw();

}

}

classRectangleextendsShape

{

publicvoiddraw()

{

System.out.println("Drawing Rectangle");

}

}

classCircleextendsShape

{

publicvoiddraw()

{

System.out.println("Drawing Circle");

}

}

When you run above program, you will get below output:

Drawing Rectangle
Drawing Circle

Please note that we are assigning child object to parent object here.

1

2

3

Shapes=newRectangle();

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.