Where to use key word static?
- method
- field
1 | public class Koala{ |
Why we need it?
- for utility or helper methods that don’t require any object state
- for state that is shared by all instances of a class, like a counter
How to call a static variable or method?
1 | Koala k = new Koala(); |
- by classname, like Koala.count
- by instance, like k.count, although k is null, k.count still works
Static Methods (vs. Instance)
1 | public class Static { |
third() is a instance method, so it cannot be inferred to static. There are two ways to modify,
add static to third() method, but name should changed to static as well
call in this way new Static().third()
Remember two rules,
- an instance method can call a static method
- a static method cannot call an instance method
Easy to understand, assume a non-static variable is inside a static method, when static method and variables are loaded into static area at the begining of the program, the non-static stuffs cannot be initialized at that time because they are determined by the runtime.
Static Variables
Some static variales are meant to change as the program runs
1
2
3public class Counter {
private static int counter = 0;
}Some static variales are meant to never change over time
1
2
3
4private static final int NUM_BUCKETS = 45;
public static void main(String[] args){
NUM_BUCKETS = 5; // DOES NOT COMPILE
}
1
2
3
4
5
6
7
8
private static final ArrayList<String> values = new ArrayList<>();
public static void main(String[] args){
values.add("changed"); // it works
}
/**
this list 'values' can add more elements
as long as its reference is not changed
*/
Static Initialization(静态块)
1 | private static final int NUM_SECONDS_PER_HOUR; |
It is just like unnamed methods.
There is an special example we should notice.
1 | private static int one; |
The static variables with final must be initialized in the static initialization or at the declaration moment. Once initialized, they cannot be changed.
Static import
Please refer to javase import
Also, static imports are for importing static members of classes.
1 | import java.util.List; |