1.

Compile-time vs Runtime Polymorphism in Java

Answer»

The following is the COMPARISON:

BasisCompile-time PolymorphismRun-time Polymorphism
Definition

Alternate nameCompile-time Polymorphism is also known as Static PolymorphismRuntime Polymorphism is also known as Dynamic Polymorphism
OccurrenceIt occurs during compile timeIt occurs during runtime
IMPLEMENTATIONIt is implemented through Method OverloadingIt is implemented through Method Overriding
SpeedMethod Execution is quickerMethod Execution is slower
FeatureIt increases the readability of the programIt provides specific implementation to the program

An EXAMPLE for the implementation of compile time polymorphism using method overloading is given below:

class Overload {    public void display(char C)    {         System.out.println(c);    }    public void display(char c, int num)      {         System.out.println(c + " "+num);    } } public class Example {   public static void main(String args[])   {       Overload obj = new Overload();       obj.display('s');       obj.display('s',12);   } }

The output of the above program is:

$JAVAC Example.java $java Example s s 12

An example for the implementation of run-time polymorphism using method overriding is given as follows:

class SuperClass {    void display() { System.out.println("SuperClass"); } } class SubClass extends SuperClass {    void display()    {        System.out.println("Subclass");    } } public class Example {    public static void main(String[] args)    {        SuperClass obj1 = new SuperClass();        obj1.display();        SuperClass obj2 = new SubClass();        obj2.display();    } }

The output is as follows:

$javac Example.java $java Example SuperClass Subclass


Discussion

No Comment Found