here is the code
public class ClassResolution {
static class Parent {
public static String name;
static {
System.out.println("this is Parent");
name = "Parent";
}
}
static class Child extends Parent {
static {
System.out.println("this is Child");
name = "Child";
}
}
public static void main(String[] args) throws ClassNotFoundException {
System.out.println(Child.name);
}}
what ouput i expect is:
this is Parent
this is Child
Child
but actually is:
this is Parent
Parent
it seems static block in Child class does not get executed, but why? it's anti-intuition, doesn't it?
supplement:
to make it more clear, i list the 2 1 points below:
- As @axtavt say, according to JLS 12.4.1, class Child is loaded, but not initialized.
But @Alexei Kaigorodov pointed out, according to jvms-5.5, class Child should be initialized, because of the execution of instruction getstatic on Child class.
what do you think?
supplement2:
@Alexei Kaigorodov has renewed his mind, so it seems no disagreement left. But I think the point of Alexei Kaigorodov is enlightening, so I left it there.
Thank you, everyone.
See Question&Answers more detail:os