Java Reference
In-Depth Information
Display 5.4
A Static Variable (part 2 of 2)
36 public class StaticDemo
37 {
38 public static void main(String[] args)
39 {
40 TurnTaker lover1 = new TurnTaker("Romeo", 1);
41 TurnTaker lover2 = new TurnTaker("Juliet", 3);
42 for (int i = 1; i < 5; i++)
43 {
44 System.out.println("Turn = " + TurnTaker.getTurn());
45 if (lover1.isMyTurn())
46 System.out.println("Love from" + lover1.getName());
47 if (lover2.isMyTurn())
48 System.out.println("Love from" + lover2.getName());
49 }
50 }
51 }
This is the file
StaticDemo.java.
Sample Dialogue
Turn = 1
Love from Romeo
Turn = 2
Turn = 3
Love from Juliet
Turn = 4
Another example of a static variable is given in Display 5.5. The static variable
numberOfInvocations is used to keep track of how many invocations have been
made by all objects of the class StaticDemo . The program counts all invocations of the
methods defined in Display 5.4, except for the method main .
Display 5.5
A Static Variable (part 1 of 2)
1 public class InvocationCounter
2 {
3 private static int numberOfInvocations = 0;
4 public void demoMethod()
5 {
6 numberOfInvocations++;
7 //In a real example, more code would go here.
8 }
object1 and object2 use
the same static variable
numberOfInvocations.
 
Search WWH ::




Custom Search