Home Segments Top Top Previous Next

150: Mainline

You tell Java about class variables in much the same way that you tell Java about local variables, but there are important differences. First, you declare the class variables inside the body of the class definition, but not inside the body of any method definition. Second, you mark class-variable declarations with the static keyword, to distinguish them from instance variables, which you learn about in Chapter 9.

The following, for example, declares wScript, a class variable meant to capture a weight.

public class Movie { 
 public static int wScript; 
        ------ --- -------- 
          ^     ^    ^ 
          |     |    *-- Variable name 
          |     *-- Variable type 
          *-- Class-variable marker 
 // Rest of class definition 
} 

And just as you can initialize local variables, you also can initialize class variables:

public class Movie { 
 // Define class variables: 
 public static int wScript = 6; 
 ...                         ^ 
}                            *-- Initial value