Tag Archives: stat

Types of polymorphism in java

In this post I will simplify the concepts of types of polymorphism in java  with the help of  method overloading and method overriding.
In java- Runtime polymorhism( Dynamic polymorphism) and Compile time polymorphism (static polymorphism).

Runtime polymorphism( Dynamic polymorphism)

  • Best example for Runtime polymorphism is method overriding.
  • In runtime polymorphism a reference class can hold object of itself and object of any class which extends reference class.
    • Ex :- A class animal can hold object of class animal and object of class cow  which is subclass of animal.
  • Following statements are correct
    • Animal obj1 = New Animal();
    • Animal obj2 = New cow();
  • In case of method overriding both classes have  same method so at compile time it is not clear which method should be called. So at run time JVM decides which method to call . This is why this concept is know as Runtime polymorphism.
  • Here is example for detailed understanding.
public class Animal
{
    public void sound() //Base class method
    {
        System.out.println ("hello, this is sound from class Animal");
    }
}

public class Cow extends Animal
{
    public void sound() //Derived Class method
    {
        System.out.println ("hello, this is sound from class Cow");
    }
}
public class A
{
   public static void main (String args []) {
       Animal obj1 = new Animal(); // Reference and object Animal
       Animal obj2 = new Cow(); // Animal reference but Cow object
       obj1.sound();
       obj2.sound();
   }
}

output:-
hello, this is sound from class Animal
hello, this is sound from class Cow
 

 

 

Compile time Polymorphism( Static polymorphism)

In java Compile time polymorphism is synonym to method overloading . In method overloading a class can have more than one methods with same name but different number of arguments or different types of arguments or both.

Following Example will help to understand the idea

class Area
{
   void calculateArea(int length, int breadth)
   {
       System.out.println ("Area of rectangle :" + (lengh * breadth));
   }
   void calculateArea(int radius)
   {
       System.out.println ("Area of Circle is:" +(3.142*r*r));
   }
   double calculateArea(double a) {
       System.out.println("Surface area of cube is :" + (6*a*a));
      }
}

class A
{
   public static void main (String args [])
   {
       Area Obj = new Area();
      
       Obj.calculateArea(20,30);
       Obj.calculateArea(7.7);
       Obj.calculateArea(7.12)
   }
}


Output
Area of rectangle is: 600
Area of Circle is : 186.27

Surface area of cube is : 304.17

In above code class Area has 3 methods with same name (calculateArea) but with different number of argument or different type of arguments. Here compiler can figure out which method to call at compile time hence this concept is called as Compile time polymorphism.