What is Static polymorphism and dynamic polymorphism in JAVA


 I would suggest you to read about Polymorphism in JAVA before reading this post. 
 There are two types of polymorphism
    i] static polymorphism
    ii] Dynamic polymorphism

Static polymorphism
           In method overloading,calls to the overloaded methods will be resolved during compile time.
When a method is called using object,if the methods are overloaded,then which method is to be called is resolved during compile time.Hence it is known as static polymorphism.

Dynamic polymorphism or runtime polymorphism
        In method overridding, calls to the overrided methods will be resolved during runtime.
Consider the below scenario .

         Animal animal=new Animal();
 animal.run();     // calls run() method in Animal class

 Gangaroo garoo=new Gangaroo();
  garoo.run();      // calls run() method in Gangaroo class

 Animal animal=new Gangaroo();
 animal.run();      // calls run() method in Gangaroo class  -  Runtime polymorphism

In the last scenario,even though the reference is animal , run() method is called based on the object created .This is decided during run time by JVM.Hence method overriding is called Runtime polymorphism or dynamic polymorphism.

   
Previous
Next Post »