static is a Java keyword. It can be applied to a field, a method or an inner class. A static field, method or class has a single instance for the whole class that defines it, even if there is no instance of this class in the program. For instance, a Java entry point (
main()) has to be static. A static method cannot be
abstract. It must be placed before the variable type or the method return type. It is recommended to place it after the access modifier and before the
|Code section 1: Static field and method.
The static items can be called on an instantiated object or directly on the class:
|Code section 2: Static item calls.
Static methods cannot call non static methods. The
this current object reference is also not available in static methods.
- Static variables can be used as data sharing amongst objects of the same class. For example to implement a counter that stores the number of objects created at a given time can be defined as so:
|Code listing 1: CountedObject.java
counter variable is incremented each time an object is created.
Public static variable should not be used, as these become global variables that can be accessed from everywhere in the program. Global constants can be used, however. See below:
|Code section 3: Constant definition.
- Static methods can be used for utility functions or for functions that do not belong to any particular object. For example:
|Code listing 2: ArithmeticToolbox.java
- See also Static methods