Static
For static variable value is the same for all instances of class. This variable initialise the first time the class appears
public class HelloWorld {
public static void main(String[] args) {
new Duck();
new Duck();
}
}
class Duck {
public static int duckCount = 0;
public Duck() {
duckCount++;
System.out.println("Duck count is " + duckCount);;
}
}
The Duck
object doesn't keep its own copy of duckCount
. Because it's static, it share a single copy of it.
Note: static variables are initalised before any of the object is created and any static method of the class run
In combination with Final
Common use to stimulate the behaviour of a constant. Now we can use Final itself to indicate a constant but static
emphasize that the variable is created once (and share access at the class level).
Without static
the variable will be created at each instance.
We can declare like this
public class HelloWorld {
public static final String MY_VAR = "never change";
}
or we can use a static initaliser:
public class HelloWorld {
public static final String MY_VAR;
static {
// this execute as soon as the class is loaded.
MY_VAR = "never change";
}
}