Sunday 16 November 2014

Polymorphism or simply In many forms

Polymorphism means many forms.
In computer terms we relate polymorphism as one of the founding stones of OOP and many Programming Languages.

When an Object has the ability to take more than one form it is referred to as Polymorphic. When a parent class reference is used to point to an object of it's child it is termed as a polymorphic reference.

When we talk about method polymorphism in Java, Compile Time and Run Time are two of its types.

Compile Time Polymorphism or Method Overloading is achieved when the methods have the same name and quite possibly process the input in a similar manner but take different inputs; either the number or the types of input are different. Method Overloading works when all the methods that you wish to overload are in the exact same class.
Let's take an example ...
public class JavaBlink {
    // This method takes two arguments and return there sum
    public int sum(int o1, int o2) {
        return o1 + o2;
    }
   
    // This method takes three arguments and return there sum
    public int sum(int o1, int o2, int o3) {
        return o1 + o2 + o3;
    }
In the example above you could see that I have used different number of arguments and overloaded the method sum. This is one of the simplest forms of method overloading.

Run Time Polymorphism on the other hand, as the name suggests, happens when the program is actually executed after compilation. This requires at least two classes or one class and one interface, both of which should be in a hierarchy.
Let's take an example ...
public class Earth {
    public float checkGravity() {
        return 9.78f;
    }
}

public class Moon extends Earth {
    public float checkGravity() {
        return 1.622f;
    }
}

public class Tester {
    public static void main(String[] a) {
    // creates an object of type Earth with reference type Earth
        Earth earth = new Earth();      
  
    // creates an object of type Moon with reference type Moon
        Moon moon = new Moon();      
       
    // creates an object of type Moon with reference type Earth
    // This is where the polymorphism kicks in; At runtime the call
    //    is sent to Moon's checkGravity()
        Earth polyMoon = new Moon();  
       
        System.out.println(earth.checkGravity());
        System.out.println(moon.checkGravity());
        System.out.println(polyMoon.checkGravity());
    }
}

In Java, specifically, we can use polymorphism in a variety of ways ...

1. Methods can be made polymorphic to cater to a wide variety of inputs
2. Polymorphic references as method arguments can be used where a variety of SubTypes could be passed; though care should be taken when calling methods on received objects
3. Polymorphism is the driving force behind Strategy Design Pattern