- In java, it is possible to define two or more methods within the same class that share the same name, but their parameter declarations are different.
- When this is the case, the methods are said to be overloaded and the process is referred to as overloading.
- Method overloading is one of the way that java implements polymorphism.
- When an overloaded method is invoked java uses the type and number of arguments of the method to determine which version of the overloaded method to actually call.
- The overloaded method must differ in the type and number of their parameters.
- While overloaded may have same number of arguments and different return type, it is in sufficient to distinguish two version of a method.
- When java encounters a call to an overloaded method, it is simply executes the version of the method whose parameters matches the arguments used in the call.
example:- consider the following example
import java.io.*;
import java.util.*;
class OverloadDemo
{
void test()
{
System.out.println(" no parameters");
}
void test(int a)
{
System.out.println(" a="+a);
void test(int a,int b)
{
System.out.println(" a & b="+a+""+b);
}
double test(double a)
{
System.out.println("double of a="+a);
return a*a;
}
}
class Overload
{
public static void main(String[] args)
{
OverloadDemo ob=new OverloadDemo();
double result=ob.test(123.25);
ob.test();
ob.test(10);
ob.test(10,20);
System.out.println(" result of ob.test(123.25)"=+result);
}
}
- Here test () is overloaded four times
- First version takes no parameters, and fourth version takes one double parameter.
- It is also returns the result relative to overloading. It is insufficient to distinguish two methods, but the return types do not play a major role in overloading.
- When an overloaded method is called, java look for a match between the arguments used to call the methods parameters.
- However this method not always is exact.
- In some cases, java’s automatic type conversion can play a role in overload resolution.
class OverloadDemo
{
void test()
{
System.out.println(" no parameters");
}
void test(int a,int b)
{
system.out.printl(" a and b are="+a +""+b);
}
void test(double a)
{
System.out,println(" inside test(double)a=" +a);
}
}
class overload
{
public static void main(String[] args)
{
OverloadDemo ob=new OverloadDemo();
int i=8;
ob.test();
ob.test(10,20);
ob.test(i);// this will invoke test(double);
ob.test(123.25);// this will invoke test(double);
}
}
0 comments :
Post a Comment
Note: only a member of this blog may post a comment.