v2
is null when it enters A's c'tor at the first time, but if I put v2
's declaration & initialization before instance
it will have a value; why is this?
public class A {
private static final String v1 = new String(new byte[]{'a', 'b'});
private static A instance = new A();
private static final String v2 = new String(new byte[]{'b', 'c'});
private A() {
System.out.printf("A c'torv1 [%s]v2 [%s]
", v1, v2);
}
public static void main(String[] args) {
System.out.println("start main");
new A();
System.out.println("end main");
}
}
output:
A c'tor v1 [ab] v2 [null]
start main
A c'tor v1 [ab] v2 [bc]
end main
Also, if I change v2
's initialization to instead be:
private static final String v2 = "ab";
it does initialize v2
, and the output is:
A c'tor v1 [ab] v2 [ab]
start main
A c'tor v1 [ab] v2 [ab]
end main
Edit
another test for the second part:
public class A {
private static final String v1 = new String(new byte[]{'a', 'b'});
private static transient A instance = new A();
private static final String v2 = new String(new byte[]{'b', 'c'});
private static final String v3 = new String("ab");
private static final String v4 = "ab";
private A() {
System.out.printf("A c'torv1 [%s] v2 [%s] v3 [%s] v4 [%s]
", v1, v2, v3, v4);
}
public static void main(String[] args) {
System.out.println("start main");
new A();
System.out.println("end main");
}
}
output:
A c'tor v1 [ab] v2 [null] v3 [null] v4 [ab]
start main
A c'tor v1 [ab] v2 [bc] v3 [ab] v4 [ab]
end main
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…