Java Reference
In-Depth Information
the value (
10
) of field
x
again (lines 43-44) before returning. The next time method
use-
Field
is called (line 20), the field has its modified value (
10
), so the method outputs
10
,
then
100
. Finally, in method
main
, the program outputs the value of local variable
x
again
(line 22) to show that none of the method calls modified
main
's local variable
x
, because
the methods all referred to variables named
x
in other scopes.
Principle of Least Privilege
In a general sense, “things” should have the capabilities they need to get their job done,
but no more. An example is the scope of a variable. A variable should not be visible when
it's not needed.
Good Programming Practice 6.3
Declare variables as close to where they're first used as possible.
Methods of the
same
name can be declared in the same class, as long as they have
different
sets of parameters
(determined by the number, types and order of the parameters)—this
is called
method overloading
. When an overloaded method is called, the compiler selects
the appropriate method by examining the number, types and order of the arguments in
the call. Method overloading is commonly used to create several methods with the
same
name that perform the
same
or
similar
tasks, but on
different
types or
different
numbers of
arguments. For example,
Math
methods
abs
,
min
and
max
(summarized in Section 6.3) are
overloaded with four versions each:
1.
One with two
double
parameters.
2.
One with two
float
parameters.
3.
One with two
int
parameters.
4.
One with two
long
parameters.
Our next example demonstrates declaring and invoking overloaded methods. We demon-
strate overloaded constructors in Chapter 8.
Declaring Overloaded Methods
Class
MethodOverload
(Fig. 6.10) includes two overloaded versions of method
square
—
one that calculates the square of an
int
(and returns an
int
) and one that calculates the
square of a
double
(and returns a
double
). Although these methods have the same name
and similar parameter lists and bodies, think of them simply as
different
methods. It may
help to think of the method names as “
square
of
int
” and “
square
of
double
,” respectively.
1
// Fig. 6.10: MethodOverload.java
2
// Overloaded method declarations.
3
4
public class
MethodOverload
5
{
Fig. 6.10
|
Overloaded method declarations. (Part 1 of 2.)