Java Reference
In-Depth Information
As we can see from the diagram, the instance variables ( xPosition and yPosition ) are
stored in each object. Because we have created three objects, we have three independent copies
of these variables.
The class variable GRAVITY , on the other hand, is stored in the class itself. As a result, there is
always exactly one copy of this variable, independent of the number of created instances.
Source code in the class can access (read and set) this kind of variable just as it can an instance
variable. The class variable can be accessed from any of the class's instances. As a result, the
objects share this variable.
Class variables are frequently used if a value should always be the same for all instances of a
class. Instead of storing one copy of the same value in each object, which would be a waste of
space and might be hard to coordinate, a single value can be shared among all instances.
Java also supports class methods (also known as static methods ), which are methods that
belong to a class. We shall discuss those later.
5.13.2
Constants
One frequent use for the static keyword is to define constants. Constants are similar to vari-
ables, but they cannot change their value during the execution of an application. In Java, con-
stants are defined with the keyword final . For example:
private final int SIZE = 10;
Here, we define a constant named SIZE with the value 10. We notice that constant declarations
look similar to field declarations, with two differences:
they include the keyword final before the type name; and
they must be initialized with a value at the point of declaration.
If a value is intended not to change, it is a good idea to declare it final . This ensures that it
cannot accidentally be changed later. Any attempt to change a constant field will result in a
compile-time error message. Constants are, by convention, often written in capital letters. We
will follow that convention in this topic.
In practice, it is frequently the case that constants apply to all instances of a class. In this situa-
tion, we declare class constants. Class constants are constant class fields. They are declared by
using a combination of the static and final keywords. For example:
private static final int SIZE = 10;
The definition of GRAVITY from our bouncing-ball project is another example of such a
constant. This is the style in which constants are defined most of the time. Instance-specific
constants are much less frequently used.
We have encountered two more examples of constants in the scribble project. The first example
was two constants used in the Pen class to define the size of the “random squiggle” (go back
to the project and find them!). The second example was the use of the color constants in that
project, such as Color.RED . In that case, we did not define the constants, but instead used con-
stants defined in another class.
 
Search WWH ::




Custom Search