static Java Keyword

The static keyword may be applied to an inner class (a class defined within another class), method or field (a member variable of a class).

Examples

  public class MyPublicClass
  {
     public final static int MAX_OBJECTS = 100;
     static int _numObjects = 0;
	 
     static class MyStaticClass
     {
     }
     
     static int getNumObjects()
     {
     }
  } 
  

Remarks

  • In general, the static keyword means that the entity to which it is applied is available outside any particular instance of the class in which the entity is declared.

  • A static (inner) class may be instantiated and reference by other classes as though it were a top-level class. In the example above, code in another class could instantiate the MyStaticClass class by qualifiying it's name with the containing class name, as MyClass.MyStaticClass.

  • A static field (member variable of a class) exists once across all instances of the class.

  • A static method may be called from outside the class without first instantiating the class. Such a reference always includes the class name as a qualifier of the method call. In the example above code outside the MyClass class would invoke the getNumObjects() static method as MyClass.getNumObjects().

  • The pattern:

    public final static <type> varName = <value>;

    is commonly used to declare class constants that may be used from outside the class. A reference to such a constant is qualified with the class name. In the example above, another class could reference the MAX_OBJECTS constant as MyClass.MAX_OBJECTS.

  • Related Topics

    final Java Keyword