Static initializations, is executed only once: the first time you make an object of that class or the first time you access a static member of that class (even if you never make an object of that class).
// housekeeping/ExplicitStatic.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Explicit static initialization with "static" clause
class Cup {
Cup(int marker) {
System.out.println("Cup(" + marker + ")");
}
void f(int marker) {
System.out.println("f(" + marker + ")");
}
}
class Cups {
static Cup cup1;
static Cup cup2;
static {
cup1 = new Cup(1);
cup2 = new Cup(2);
}
Cups() {
System.out.println("Cups()");
}
}
public class ExplicitStatic {
public static void main(String[] args) {
System.out.println("Inside main()");
Cups.cup1.f(99); // [1]
}
// static Cups cups1 = new Cups(); // [2]
// static Cups cups2 = new Cups(); // [2]
}
/* When [1] is uncommented, [2] are commented. Output:
Inside main()
Cup(1)
Cup(2)
f(99)
When both [1] and [2] are uncommented. Output:
Cup(1)
Cup(2)
Cups()
Cups()
Inside main()
f(99)
When [1] is commented, [2] are uncommented. Output:
Cup(1)
Cup(2)
Cups()
Cups()
Inside main()
When both [1] and [2] are commented. Output:
Inside main()
*/
then change the code order
// housekeeping/ExplicitStatic.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Explicit static initialization with "static" clause
class Cup {
Cup(int marker) {
System.out.println("Cup(" + marker + ")");
}
void f(int marker) {
System.out.println("f(" + marker + ")");
}
}
class Cups {
static {
// cup1 = new Cup(1);
cup2 = new Cup(2);
}
static Cup cup1 = new Cup(1);
static Cup cup2;
Cups() {
System.out.println("Cups()");
}
}
public class ExplicitStatic {
public static void main(String[] args) {
System.out.println("Inside main()");
Cups.cup1.f(99); // [1]
}
// static Cups cups1 = new Cups(); // [2]
// static Cups cups2 = new Cups(); // [2]
}
/* My Output:
Inside main()
Cup(2)
Cup(1)
f(99)
*/
for better understand, please read below content.
see initialization with inheritance.
references:
1. On Java 8 - Bruce Eckel
2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/housekeeping/ExplicitStatic.java