Overloading is about reusing the same method name with different arguments and sometimes different return type. Some basic rules apply:
• In the class that defines de original method, or a subclass of that class, the method name can be reused if the argument list differs in terms of the type of at least one argument.
• A difference in return type alone is insufficient to constitute an overload and is illegal.
Example #1:
public static void main(String args[]) {
System.out.println( DoubleIt("Hello world") );
System.out.println( DoubleIt(15) );
}
static String DoubleIt(String name) {
name += " " + name;
return name;
}
static String DoubleIt(int id) {
id *= 2;
return Integer.toString(id);
}
Result:
Hello Hello
30
Example #2:
int MyMethod(int a) { }
float MyMethod(int a) { } // ERROR!!!. Difference in return type alone
// is insufficient to constitute an overload.
Example #3:
int MyMethod(int value) { }
float MyMethod(int number) { } // ERROR!!!. The types should be
// different, not the variable names.
Invoking Overloaded Methods
Method overloaded names are effectively independent methods. Using the same name is just a convenience to the programmer. Overloaded methods may call one another simply by providing a normal method call with an appropriately formed argument list.
Example:
public static void main(String args[]) {
allStars(15);
}
static void allStars(String name) {
name = "*** " + name + " ***";
System.out.println(name);
}
static void allStars(int id) {
String s = ""+id;
allStars(s);
}
In this example, we have created a method to show names surrounded by stars, we also wanted to accept int values, so we added a method that receives ints but converts them to strings and passes the result to the original string method.
Dec012007
Dec
01
2007
OVERLOADING
Posted by gautam at Saturday, December 01, 2007
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment