Java Reference
In-Depth Information
Method Signature
The name of a method, along with its number and type of parameters.
Method Overloading
The ability to define two or more different methods with the same name but
different method signatures.
The two example drawBox versions clearly have different method signatures, because
one has two parameters and the other has zero parameters. It would be obvious from any
call on the method which version to use: If you see two parameters, you execute the ver-
sion with two parameters; if you see zero parameters, you execute the version with zero
parameters.
The situation gets more complicated when overloading involves the same number of
parameters, but this turns out to be one of the most useful applications of overloading.
For example, the println method is actually a series of overloaded methods. We can
call println passing it a String , an int ,a double , and so on. This flexibility is
implemented as a series of different methods, all of which take one parameter: One ver-
sion takes a String , another version takes an int , another version takes a double , and
so on. Obviously, you do slightly different things to print one of these kinds of data ver-
sus another, which is why it's useful to have these different versions of the method.
3.2 Methods That Return Values
The last few methods we've looked at have been action-oriented methods that per-
form some specific task. You can think of them as being like commands that you
could give someone, as in “Draw a box” or “Draw a triangle.” Parameters allow these
commands to be more flexible, as in “Draw a box that is 10 by 20.”
You will also want to be able to write methods that compute values. These meth-
ods are more like questions, as in “What is the square root of 2.5?” or “What do you
get when you carry 2.3 to the 4 th power?” Consider, for example, a method called
sqrt that would compute the square root of a number.
It might seem that the way to write such a method would be to have it accept a
parameter of type double and println its square root to the console. But you may
want to use the square root as part of a larger expression or computation, such as solv-
ing a quadratic equation or computing the distance between points on an x / y plane.
A better solution would be a square root command that passes the number of inter-
est as a parameter and returns its square root back to the program as a result. You
could then use the result as part of an expression, store it in a variable, or print it to
the console. Such a command is a new type of method that is said to return a value.
 
Search WWH ::




Custom Search