1.

What is Compile time Polymorphism and how is it different from Runtime Polymorphism?

Answer»

COMPILE Time Polymorphism: Compile time polymorphism, also known as Static Polymorphism, refers to the TYPE of Polymorphism that happens at compile time. What it means is that the compiler DECIDES what shape or value has to be taken by the entity in the picture.

Example:

// In this program, we will see how multiple functions are created with the same name, // but the compiler decides which function to call easily at the compile time itself.class CompileTimePolymorphism{ // 1st method with name add public int add(int x, int y){ return x+y; } // 2nd method with name add public int add(int x, int y, int z){ return x+y+z; } // 3rd method with name add public int add(double x, int y){ return (int)x+y; } // 4th method with name add public int add(int x, double y){ return x+(int)y; }}class Test{ public static void main(String[] args){ CompileTimePolymorphism demo=new CompileTimePolymorphism(); // In the below statement, the Compiler looks at the ARGUMENT types and decides to call method 1 System.out.println(demo.add(2,3)); // Similarly, in the below statement, the compiler calls method 2 System.out.println(demo.add(2,3,4)); // Similarly, in the below statement, the compiler calls method 4 System.out.println(demo.add(2,3.4)); // Similarly, in the below statement, the compiler calls method 3 System.out.println(demo.add(2.5,3)); }}

In the above example, there are four versions of add methods. The FIRST method takes two parameters while the second one takes three. For the third and fourth methods, there is a change of order of parameters. The compiler looks at the method signature and decides which method to invoke for a particular method call at compile time.

Runtime Polymorphism: Runtime polymorphism, also known as Dynamic Polymorphism, refers to the type of Polymorphism that happens at the run time. What it means is it can't be decided by the compiler. Therefore what shape or value has to be taken depends upon the execution. Hence the name Runtime Polymorphism.

Example:

class AnyVehicle{ public void move(){ System.out.println(“Any vehicle should move!!”); }}class Bike extends AnyVehicle{ public void move(){ System.out.println(“Bike can move too!!”); }}class Test{ public static void main(String[] args){ AnyVehicle vehicle = new Bike(); // In the above statement, as you can see, the object vehicle is of type AnyVehicle // But the output of the below statement will be “Bike can move too!!”,  // because the actual implementation of object ‘vehicle’ is decided during runtime vehicle.move(); vehicle = new AnyVehicle(); // Now, the output of the below statement will be “Any vehicle should move!!”,  vehicle.move(); }}

As the method to call is determined at runtime, as shown in the above code, this is called runtime polymorphism. 



Discussion

No Comment Found