static vs dynamic

Posted: June 20, 2012 in Java

Static Vs Dynamic binding

Static Polymorphism:

The Polymorphism exhibited at compile time is called static polymorphism. Here Java Compiler knows without any ambiguity which method is called at the time of compilation. Of Course, JVM executes the method later, but the compiler knows and can bind the method call with method code(body) at the time of compilation. So, it is called ‘static binding’ or ‘compile time polymorphism’.

Static methods, private methods, and final methods and variables are examples for static polymorphism. The reason is that all of those methods maintain single copy in memory that is available to the objects of the class. So the java compiler knows which method is called at the time of compilation and it needs not wait till the objects are created.

class One{

static void calculate(double x)

{

System.out.println(“Square Value   “+(x*x));

}

}

class Two extends One{

static void calculate(double x)

{                              System.out.println(“Square Root   “+Math.sqrt(x));

}

}

 

public class StaticPoly {

public static void main(String[] args) {

One o = new Two();

o.calculate(25);

}

}

Output :

Square Value   625.0

Dynamic Polymorphism:

The Polymorphism exhibited at runtime is called dynamic polymorphism. This means when a method is called, the method call bound to the method body at the time of running the program, dynamically. In this case, java compiler does not which method is called at the time of compilation. Only JVM knows at runtime which method is to be executed.

class One{

void calculate(double x)

{

System.out.println(“Square Value   “+(x*x));

}

}

class Two extends One{

void calculate(double x)

{

System.out.println(“Square Root   “+Math.sqrt(x));

}

}

 

public class DynamicPoly {

public static void main(String[] args) {

One o = new Two();

o.calculate(25);

}

}

 

output:  

Square Root   5.0

Who will decide which method is to be executed? Is it java compiler or JVM?

Methods are called by using an object, the java compiler can not decide at the time of compilation which method is actually called by user. It has to wait till the object is created for class. And creation objects take place at runtime by jvm. Now jvm should decide which method is actually called by user at runtime(dynamically).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s