For example, the following code will print 10 instead of 15. Why? Does static variables comes first? And why can't we print like System.out.println(k) ?
public class Test {
static {
//System.out.println(k); => compile-time error but=>
//System.out.println(Test.k); => works
k = 15;
}
static int k = 10;
public static void main(String[] args) {
System.out.println(k);
}
}
From what I can see, the main method can't see the variable k = 15 because it's in a different scope. Nothing related to the things you mentioned.
Static blocks and variables are initiated in the order of how they appear in the code. It is guaranteed by jvm
Your original code doesn't show things properly because you are shadowing the class variable k.
Обсуждают сегодня