Java Programming/Keywords/static
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 final
keyword:
Code section 1: Static field and method.
public static final double PI = 3.1415926535;
public static void main(final String[] arguments) {
//…
}
|
The static items can be called on an instantiated object or directly on the class:
Code section 2: Static item calls.
double aNumber = MyClass.PI;
MyClass.main(new String[0]);
|
Static methods cannot call nonstatic methods. The this
current object reference is also not available in static methods.
Interest
edit- 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
public CountedObject {
private static int counter;
…
public AClass() {
…
counter++;
}
…
public int getNumberOfObjectsCreated() {
return counter;
}
}
|
The 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.
public static final String CONSTANT_VAR = "Const";
|
- 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
public ArithmeticToolbox {
…
public static int addTwoNumbers(final int firstNumber, final int secondNumber) {
return firstNumber + secondNumber;
}
}
|
- See also Static methods