Java Reference
In-Depth Information
Static Variables
A
static variable
belongs to the class as a whole. All objects of the class can read and change
the static variable. Static variables should normally be private, unless they happen to be defined
constants.
SYNTAX
private static
Type
Variable_Name
;
private static
Type
Variable_Name = Initial_Value
;
public static final
Type
Variable_Name
=
Constant_Value
;
EXAMPLES
private static
String lastUser;
private static int
turn = 0;
public static final double
PI = 3.14159;
Self-Test Exercises
7. What is the difference between a static variable and an instance variable?
8. Can you use an
instance variable
(without an object name and dot) in the defini-
tion of a
static method
of the same class? Can you use an
instance variable
(with-
out an object name and dot) in the definition of a
nonstatic (ordinary) method
of
the same class?
9. Can you use a
static variable
in the definition of a
static method
of the same class?
Can you use a
static variable
in the definition of a
nonstatic (ordinary) method
of
the same class?
10. Can you use the
this
parameter in the definition of a static method?
11. When we defined the class
Date
in Display 4.11 in Chapter 4, we had not yet
discussed static methods, so we did not mark any of the methods
static
. How-
ever, some of the methods could have been marked
static
(and should have
been marked
static
, if only we'd known what that meant). Which of the meth-
ods can be marked
static
? (If you omit the modifier
static
when it is appropri-
ate, then the method cannot be invoked with the class name; it must be invoked
with a calling object.)
12. Following the style guidelines given in this topic, when should a static variable be
marked
private
?
13. What do static methods and static variables have in common? After all, they are
both called
static,
so it sounds like they have something in common.