1   // Example 3.1 joi/examples/StaticDemo.java
2   //
3   //
4   // Copyright 2003 Bill Campbell and Ethan Bolker
5   
6   // Demonstrate the interplay between static members (fields and methods)
7   // and instance (non-static) members.
8   //
9   // %> java StaticDemo
10  // 0: counter = 1; objectField = 0
11  // StaticDemo.classMethod() = 100
12  // classMethod() = 100
13  // 1: counter = 2; objectField = 1
14  // StaticDemo.classMethod() = 101
15  // classMethod() = 101
16  // 2: counter = 3; objectField = 2
17  // StaticDemo.classMethod() = 103
18  // classMethod() = 103
19  // 3: counter = 4; objectField = 3
20  // StaticDemo.classMethod() = 106
21  // classMethod() = 106
22  // 4: counter = 5; objectField = 4
23  // StaticDemo.classMethod() = 110
24  // classMethod() = 110
25  //
26  // last classMethod() = 110
27  
28  public class StaticDemo
29  {
30      // Declare three (static) class variables
31      // A class variable is associated with the (one) class.
32  
33      private static int counter  = 0; 
34      private static int classVar = 0; 
35      private static Terminal terminal = new Terminal(); 
36  
37      int objectField = 0;     // an instance variable; one per object
38  
39      // The constructor keeps track of how many StaticDemo objects
40      // have been constructed.
41  
42      public StaticDemo( int objectFieldValue )
43      {
44          objectField = objectFieldValue; // set the instance variable
45          counter++;  // increment counter (counting the StaicDemos made)
46      }
47  
48      public void instanceMethod()
49      {
50          // Instance methods can refer to both instance variables
51          // and class variables.
52          
53          terminal.println( "counter = " + counter + 
54                            "; objectField = " + objectField );
55          classVar = classVar + objectField;
56  
57      }
58  
59      public static int classMethod()
60      {
61          // Class methods may refer only to class variables 
62          // (and other class methods), as well as to local variables.
63  
64          // What happens if we comment out the next line?
65          int counter = 100;
66          
67          return counter + classVar;
68      }
69  
70      public static void main( String[] args )
71      {
72          for (int i = 0; i < 5; i++) {
73              StaticDemo sd = new StaticDemo( i );
74              terminal.print( i + ": " );
75              sd.instanceMethod();
76  
77              // classMethod()
78              //   is equivalent to
79              // StaticDemo.classMethod()
80              terminal.println( "StaticDemo.classMethod() = " 
81                                + StaticDemo.classMethod() );
82              terminal.println( "classMethod() = " 
83                                + classMethod() );
84          }
85          terminal.println();
86          terminal.println( "last classMethod() = " + classMethod() );
87      }
88  }
89