In order to call a method legally, you need to know its name, how many parameters it has, the type of each parameter, and the order of those parameters.
This information is called the method’s signature.
The signature of the method doMath
can be expressed as:
doMath(int, double)
Note that the signature does not include the names of the parameters. If you just want to use the method, you don't need to know what the parameter names are, so the names are not part of the signature.
Java allows two different methods in the same class to have the same name, provided that their signatures are different. This is called overloading a method.
We say that a method's name is overloaded when one name has multiple different meanings. The Java compiler doesn't get the methods mixed up because their signatures are distinct. A basic example is println
. All of these methods have different signatures, but the same name:
println(int)
println(double)
println(String)
println(char)
println(boolean)
println()
In addition to these, we have been using this concept with the DrawingTool
class and its turnLeft
method.
turnLeft()
turnLeft(120)
It is illegal to have two methods in the same class that have the same signature but have different return types. For example, it would be a syntax error for a class to contain two methods defined as:
double doMath(int a, double x){// some code}
int doMath(int b, double y){// some code}
The Java compiler cannot differentiate return values, so it uses the signature to decide which method to call.
Last modified: December 12, 2022
Back to Returning Values