Constants

In Java, we identify a constant by declaring it as final. Within the main method of the Circle class, we could have declared the PI constant as

final double PI = 3.14159;


However, PI can then be used only within the main method. If we were to add more methods to the Circle class, and want PI to be accessible to these methods, we need to declare PI within the Circle class block but outside the main method block, and prefix it with the static keyword. We have done this in line 7, as follows:

static final double PI = 3.14159;

A constant declared static is known as a class constant. We discuss the static concept further in Chapter 4. If PI were to be assigned a value subsequently in the program, this would be rejected by the compiler

No comments:

Post a Comment