Friday 5 July 2013

Method overloading in java

// siddhu vydyabhushana // 2 comments
Method overloading:
A class can contain any number of methods. Methods can be with parameter and without parameter.
The parameter in a method are called type signature.
It is possible in java to define two or more methods within the same class that share the same name, but with different parameter declarations (type signatures).
When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading.
Overloading methods demonstrate the concept of polymorphism.
When an overloaded method is invoked, java uses the type and/or number of arguments as its guide to determine which version of the overloaded method to call.
Thus, overloaded methods must differ in the type and/or number of their parameters.
Overloaded methods may have different return types.
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.
EX :
 
public class MethodOver  
{        
	int n1;
        int n2;
        MethodOver()
        {
		n1 = 10;
                n2 = 20;
        }
        void square()         
	{
        	System.out.println("The Square is " + n1 * n2);
        }
        void square(int p1)
        {         
        	n1 = p1;
                System.out.println("The Square is " + n1 * n2);     
   	}
        void square(int p1, int p2)        
	{
  		n1 = p1;
                n2 = p2; 
                System.out.println("The Square is " + n1 * n2);      
   	}
        public static void main(String args[])         
	{          
       		MethodOver obj1 = new MethodOver();
                obj1.square(); //call non parameterise method        
         	obj1.square(4);   //call method which has 1 argument   
              	obj1.square(7,8);  //call method which has 2 argument      
   	} 
}

Output :
The Square is 200
The Square is 80
The Square is 56
You can see that here we have 3 square methods with different argument.
Its called method overloading.

2 comments: