☰ Topics

Polymorphism

It is a Greek term means "ability to take more than one form". It is a concept in which same object behaves differently according to environment(argument/parameter). This concept is implemented with the help of method/constructor. It is implemented either by overloading or overriding.

In java, it is possible to define more than one function with the same name more than one time in a program but with different signature. This phenomenon is called method overloading. When we say different signature, it means different return type or different number of arguments or different type of arguments or different order of arguments. When java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call.

An example to illustrate function overloading:-

class overload
{
	public int add(int num1,int num2)
	{
		return (num1+num2);
	}
	public double add(int num1,double num2)
	{
		return (num1+num2);
	}
	public double add(int num1,double num2,int num3)
	{
		return (num1+num2+num3);
	}
	public static void main(String[] arg)
	{
		overload ob=new overload();
		System.out.println("Sum="+ob.add(5,5));      //add(int num1,int num2) will be called
		System.out.println("Sum="+ob.add(5,5.5,9));     //double add(int num1,double num2,int num3) will be called
		System.out.println("Sum="+ob.add(5,5.8));    //add(int num1,double num2) will be called

	}
}

                            

OUTPUT:-

E:\java\new_java>javac overload.java

E:\java\new_java>java overload
Sum=10
Sum=19.5
Sum=10.8
                        

It is decided at compile time itself to which function to call, therefore, it is called early binding or compile-time polymorphism.

In java, it is also to use same function more than one time having same name with same signature but having different definition. This phenomenon is called method overriding. It cannot be implemented in single class, atleast two classes are needed for it. The concept of inheritance is involved in it. It is decided during run time to which function to call, therefore, it is called late binding or run-time polymorphism. Since, the concept of overriding is completely dependent on inheritance, therefore, it is discussed in inheritance section in detail.