Java Reference
In-Depth Information
Parameters versus Constants
In Chapter 2, you saw that class constants are a useful mechanism to increase the flexi-
bility of your programs. By using such constants, you can make it easy to modify a pro-
gram to behave differently. Parameters provide much of the same flexibility, and more.
Consider the writeSpaces method. Suppose you wrote it using a class constant:
public static final int NUMBER_OF_SPACES = 10;
This approach would give you the flexibility to produce a different number of spaces,
but it has one major limitation: The constant can change only from execution to execu-
tion; it cannot change within a single execution. In other words, you can execute the pro-
gram once with one value, edit the program, recompile, and then execute it again with a
different value, but you can't use different values in a single execution of the program
using a class constant.
Parameters are more flexible. Because you specify the value to be used each time
you call the method, you can use several different values in a single program execution.
As you have seen, you can call the method many different times within a single pro-
gram execution and have it behave differently every time. However, using parameters
involves more work for the programmer than using class constants. It makes your
method headers and method calls more tedious, not to mention making the execution
(and, thus, the debugging) more complex.
Therefore, you will probably find occasion to use each technique. The basic rule is
to use a class constant when you only want to change the value from execution to exe-
cution. If you want to use different values within a single execution, use a parameter.
Overloading of Methods
You'll often want to create slight variations of the same method, passing different
parameters. For example, you could have a drawBox method that allows you to specify
a particular height and width, but you might also want to have a version that draws a
box of default size. In other words, sometimes you want to specify these values, as in
drawBox(8, 10);
and other times you want to just draw a box with the standard height and width:
drawBox();
Some programming languages require you to come up with different names
for these versions, such as drawBox and drawDefaultBox . As you can imagine,
coming up with new names for each variation becomes tedious. Fortunately,
Java allows you to have more than one method with the same name, as long as they
have different parameters. This is called overloading. The primary requirement for
overloading is that the different methods that you define must have different method
signatures.
 
Search WWH ::




Custom Search