Java Reference
In-Depth Information
Display 5.4
A Static Variable
(part 1 of 2)
1
public class
TurnTaker
2 {
3
private static int
turn = 0;
4
private int
myTurn;
5
private
String name;
6
public
TurnTaker(String theName, int theTurn)
7 {
8 name = theName;
9
if
(theTurn >= 0)
10 myTurn = theTurn;
11
else
12 {
13 System.out.println("Fatal Error.");
14 System.exit(0);
15 }
16 }
This is the file
TurnTaker.java.
17
public
TurnTaker()
18 {
19 name = "No name yet";
20 myTurn = 0;
//Indicating no turn.
21 }
22
public
String getName()
23 {
24
return name;
25 }
26
public static int
getTurn()
27 {
28 turn++;
29
return
turn;
30 }
You cannot access an instance
variable in a static method, but you
can access a static variable in a
static method.
31
public boolean
isMyTurn()
32 {
33
return
(turn == myTurn);
34 }
35 }
(continued)