Polymorphism Explained

Polymorphism in object oriented design can be explained as "One interface , mutliple methods". It allows one interface which can be used for different set of actions. Polymorphism of objects deals with accepting and responding request of a client. In simple words we can say polymorphism is like to have one form with many use.

Normally we can see two types of Polymorphism :

Compile-time polymorphism
Runtime Polymorphism


Compile-time polymorphism :

Compile-time polymorphism can be seen thorugh the method overloading in java. In case of method overloading , method which need to be invoked determined at compile time.
To overload a method we need to have different signature .Lets look at following code example.



class CompileTimePoly{
public void methodTest(String s){
System.out.println(" I am dealing with only one string ");
}
public void methodTest(String x, String y){
System.out.println(" I am dealing with two strings ");
}
}
public class PolyTest{
public static void main(String[] args){
CompileTimePoly cObj = new CompileTimePoly();

cObj.methodTest("Strings");

cObj.methodTest("Two", "String"); // In case of compile time polymorphism method gets called as per argument
}
}


Runtime Polymorphism :



In rumtime polymorphism,as the name suggest the method to be invoked is determined at the run time. We can see run time polymorphism in form of method overriding. In case of method overriding a subclass can contain a method with the same name and signature as in the Super class.


class SuperClass{
public void rider(int r){
System.out.println("The super class method called : "+ r);
}
}

class SubClass extends SuperClass{
public void rider(int r){
System.out.println("The sub class method called : "+ r);
}
}

public class PolyRide{
public static void main(String[] args){
SuperClass superObj;

superObj= new SuperClass();
superObj.rider(2); //invokes super class method

superObj=new SubClass();
obj.rider(5); // This invokes subclass method
}
}
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment