The static Attributes


The static keyword can also be applied to attributes. A (simplified) way to think of it is that a non-static member (field or method) is one which is provided by an instance, while a static member is one which is provided by a class. The static attributes are declared in a class, but outside a method, constructor, or a block.

StaticAttribute.java (static or public attributes)
public class StaticAttribute {
  public static void main( String[ ] args ) {
    int attr = 5;               // Can’t be declared as static.
    myStaticMethod( );          // Call the static method.
  }
  // A static attribute
  static int attr = 10;
  // A static method
  static void myStaticMethod( ) { System.out.println( attr ); }
}
Output:           Result:

Class variables are also known as static variables. There would only be one copy of each class variable per class, regardless of how many objects are created from it.

ClassAttribute.java (static or public attributes)
public class ClassAttribute {
  public static void main( String[ ] args ) {
    attr = 5;                   // Can’t be declared as static.
    myStaticMethod( );          // Call the static method.
  }
  // A static attribute
  static int attr = 0;
  // A static method
  static void myStaticMethod( ) { System.out.println( attr ); }
}
Output:           Result: