1Runtime polymorphism is a process of which take
2cares the overriding method at run time
3rather than compile time.
4 In method overriding,
5a subclass overrides a method with the same
6signature as that of in its superclass.
7During compile time, the check is made
8on the reference type. But, in the runtime,
9JVM figures out the object type and would
10run the method that belongs to
11that particular object.
1// In this program, we will see how multiple functions are created with the same name,
2// but the compiler decides which function to call easily at the compile time itself.
3class CompileTimePolymorphism{
4 // 1st method with name add
5 public int add(int x, int y){
6 return x+y;
7 }
8 // 2nd method with name add
9 public int add(int x, int y, int z){
10 return x+y+z;
11 }
12 // 3rd method with name add
13 public int add(double x, int y){
14 return (int)x+y;
15 }
16 // 4th method with name add
17 public int add(int x, double y){
18 return x+(int)y;
19 }
20}
21class Test{
22 public static void main(String[] args){
23 CompileTimePolymorphism demo=new CompileTimePolymorphism();
24 // In the below statement, the Compiler looks at the argument types and decides to call method 1
25 System.out.println(demo.add(2,3));
26 // Similarly, in the below statement, the compiler calls method 2
27 System.out.println(demo.add(2,3,4));
28 // Similarly, in the below statement, the compiler calls method 4
29 System.out.println(demo.add(2,3.4));
30 // Similarly, in the below statement, the compiler calls method 3
31 System.out.println(demo.add(2.5,3));
32 }
33}