Static
The Static
Keyword
static
members belong to a class rather than to an instance of a class. This allows them to be accessed Class.method()
rather than classInstance.method()
.
Examples
Given the following class:
public class Operations {
public final double pi = 3.14;
/**
* Tries to parse the given string to an integer.
* Failure returns the default.
* @param val String to parse
* @param def Default value
*/
public int tryParse(String val, int def) {
try {
return Integer.parseInt(val);
} catch (NumberFormatException e) {
return def;
}
}
}
You would need to create an instance of the Operations
class to access the tryParse()
method or pi
.
Operations op = new Operations();
op.tryParse("123", -1);
System.out.println("Pi is " + op.pi);
That’s tedious and uses up unnecessary memory. Instead, we add the static
keyword to the method.
public class Operations {
public static final double pi = 3.14;
/**
* Tries to parse the given string to an integer.
* Failure returns the default.
* @param val String to parse
* @param def Default value
*/
public static int tryParse(String val, int def) {
try {
return Integer.parseInt(val);
} catch (NumberFormatException e) {
return def;
}
}
}
Now, we can skip the step of instantiating the Operations
class:
Operations.tryParse("123", -1);
System.out.println(Operations.pi);