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. We say that the name of the method is overloaded because it has different meanings. The Java compiler doesn't get the methods mixed up. It can tell which one you want to call by the number and types of the arguments that you provide in the call statement. You have already seen overloading used in the System.out
object, which is an instance of the PrintStream
class. This class defines many different methods named println
. These methods all have different signatures, such as:
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){}
int doMath(int a, double x){}
The Java compiler cannot differentiate return values so it uses the signature to decide which method to call.