Sunday 31 July 2011

Method Overloading

METHOD OVERLOADING:
In java, it is possible to create methods that have the same name, provided they have different signatures. A signature is formed from its name, together with the number and types of its arguments. The method in return type is not considered a part of the method signature. Method overloading is used when objects are required to perform a similar task but by using different input parameters. When we call a method in an object, java matches up the method name first, and then the number and type of parameters, to decide which method to execute. This process is known as Polymorphism.

Public class Movie
{
float price;
public void setprice()
{
price=3.50;
}
public void setprice (float newprice)
{
price=newprice;
}
}
Movie mov1=new Movie();
mov1.setprice();
mov1.setprice(3.25);

As you can see setprice() is overloaded two times. The first version takes no argument and sets the price to 3.50 and second constructor takes single argument whic sets the price to 3.25.

When an overloaded method is called, java looks for a match between the argument used to call the method and the method's parameters. However, this match need not be exact. In some cases java's automatic type conversion takes the important role in overloaded resolution.

Example:
public class Movie
{
float price;
public void disp()
{
System.out.println(“No parameter”);
}
public void disp(int x, int y)
{
System.out.println(“x = ” + x + “y = “ +y);
}
public void disp(double x)
{
System.out.println(“x =” +x);
}
}
class overload
{
public static void main ( String args[])
{
Overload ob = new overload();
int i = 100;
ob.disp(); //invokes no argument constructor
ob.disp(10,20); //invokes disp(int,int)
ob.disp(i); //invokes disp (double)
ob.disp(100.50) //invokes disp(double)
}
}

Class Movie does not define disp(int). When disp(int) is called from main(), when no matching method is found, java automatically converts an integer into a double. Java uses its automatic type conversion only if no exact match is found.
Java's standard class library has abs() method. This method returns absolute value of all type of numeric types e.g. Int double, float. This method is overloaded in Math class. Whereas in 'C' language there are three methods – abs(),fabs(),labs()- to return absolute of int, float and long values respectively, the java.awt.Graphics class has six different drawImage methods.

As far as java is concerned, these are entirely different methods. The duplicate names are really just a convenience for the programmer.



No comments:

Post a Comment