Java Reference
In-Depth Information
Thus, when the number of lines is five, the appropriate value is 11 , but when the
number of lines is three, the appropriate value is 7 . Programmers call numbers like
these magic numbers. They are magic in the sense that they seem to make the pro-
gram work, but their definition is not always obvious. Glancing at the DrawCone pro-
gram, one is apt to ask, “Why 5? Why 11? Why 3? Why 7? Why me?”
To make programs more readable and more adaptable, you should try to avoid
magic numbers whenever possible. You do so by storing the magic numbers. You can
use variables to store these values, but that is misleading, given that you are trying to
represent values that don't change. Fortunately, Java offers an alternative: You can
declare values that are similar to variables but that are guaranteed to have constant
values. Not surprisingly, they are called constants. We most often define class con-
stants, which can be accessed throughout the entire class.
Class Constant
A named value that cannot be changed. A class constant can be accessed
anywhere in the class (i.e., its scope is the entire class).
You can choose a descriptive name for a constant that explains what it represents.
You can then use that name instead of referring to the specific value to make your
programs more readable and adaptable. For example, in the DrawCone program, you
might want to introduce a constant called LINES that represents the number of lines
(recall from Chapter 1 that we use all uppercase letters for constant names). You can
use that constant in place of the magic number 5 and as part of an expression to cal-
culate a value. This approach allows you to replace the magic number 11 with the
formula from which it is derived ( 2 * LINES + 1 ).
Constants are declared with the keyword final , which indicates the fact that their
values cannot be changed once assigned, as in
final int LINES = 5;
You can declare a constant anywhere you can declare a variable, but because con-
stants are often used by several different methods, we generally declare them outside
methods. This causes another run-in with our old pal, the static keyword. If you
want your static methods to be able to access your constants, the constants them-
selves must be static. Likewise, just as we declare our methods to be public, we usu-
ally declare our constants to be public. The following is the general syntax for con-
stant definitions:
public static final <type> <name> = <expression>;
For example, here are definitions for two constants:
public static final int HEIGHT = 10;
public static final int WIDTH = 20;
 
Search WWH ::




Custom Search