Method Overloading
Method Overloading
Overloading
In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different
When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading
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 actually call.
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 actually call. Then, overloaded methods must differ in the type and/or number of their parameters
While overloaded methods may have different return types; The return type alone is insufficient to distinguish two versions of a method. 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.
Code description
As you can see, test( ) is overloaded four times. The first version takes no parameters, the second takes one integer parameter, the third takes two integer parameters, and the fourth takes one double parameter.
The fact that the fourth version of test( ) also returns a value is of no consequence relative to overloading, since return types do not play a role in overload resolution.
Method overloading supports polymorphism because it is one way that Java implements the "one interface, multiple methods" paradigm
In languages that do not support method overloading, each method must be given a unique name But, frequently you will want to implement essentially the same method for different types of data.
For example consider the absolute value function; In languages that do not support overloading, there are usually three or more versions of this function, each with a slightly different name.
For instance, in C,
1.
2.
3.
the function abs( ) - returns the absolute value of an integer labs( ) returns the absolute value of a long integer fabs() returns the absolute value of a floatingpoint value
Since C does not support overloading, each function has to have its own name, even though all three functions do essentially the same thing
Indeed, Java's standard class library includes an absolute value method, called abs( ). This method is overloaded by Java's Math class to handle all numeric types. Java determines which version of abs() to call based upon the type of argument.