Java Reference
In-Depth Information
The most interesting detail in this class is the line
private static final int GRAVITY = 3;
This is a construct we have not seen yet. This one line, in fact, introduces two new keywords,
which are used together: static and final .
5.13.1 The static keyword
The keyword static is Java's syntax to define class variables. Class variables are fields that are stored
in a class itself, not in an object. This makes them fundamentally different from instance variables (the
fields we have dealt with so far). Consider this segment of code (a part of the BouncingBall class):
public class BouncingBall
{
// Effect of gravity.
private static final int GRAVITY = 3;
Concept:
Classes can have
fields. These are
known as class
variables or static
variables. Exactly
one copy exists
of a class variable
at all times, inde-
pendent of the
number of created
instances.
private int xPosition;
private int yPosition;
Other fields and method omitted.
}
Now imagine that we create three BouncingBall instances. The resulting situation is shown
in Figure 5.8.
Figure 5.8
Instance variables
and a class variable
BouncingBall
*5$9,7<
LVLQVWDQFHRI
LVLQVWDQFHRI
LVLQVWDQFHRI
EDOO%RXQFLQJ%DOO
EDOO%RXQFLQJ%DOO
[3RVLWLRQ
EDOO%RXQFLQJ%DO O
[3RVLWLRQ
\3RVLWLRQ
\3RVLWLRQ
[3RVLWLRQ
\3RVLWLRQ
 
Search WWH ::




Custom Search