2013年9月11日星期三

Experts , asked questions about the class loading


print:
A
1
But I totally do not understand why ah , B static code block why not enforce it ?
------ Solution ---------------------------------------- ----
static block is called when the jvm loaded class , B class has not been loaded , you can new B () try.
------ For reference only -------------------------------------- -
jvm not load class B class file in the main method in Canada System.out.println (Bb); class B static statement can be executed .
------ For reference only -------------------------------------- -
B.a is class A visit to the property, so loaded only a, not loaded B, visit Bb look
------ For reference only ---------------------------------------
Well, put it upstairs two right, but why not load class B yet.
First, I called the B class .
Secondly, I would class B to modify the static code block in class A variable's value. ( No syntax requirement does not allow modifications. )

However , JVM do not care I will not be modified directly load only Class A trouble , why ?
------ For reference only -------------------------------------- -
public class ClassLoaderTest {
public static void main(String[] args) throws ClassNotFoundException {
System.out.println(B.b);
}
}
class A{
static int a=1;
static{
System.out.println("A");
}
}
class B extends A{
static int b=2;
static{
System.out.println("B");
}
}

print:
A
B
2

this and the above that similar, but emphasized that b. But why A loaded yet.
------ For reference only -------------------------------------- -
Reply 4 Floor :
That is because A is the parent of B class , but also because the static constructor method is executed in the first block , we first perform a static block , but it is executed once only. This is not why, very easy to understand, a new object is not out of time , the static block ( belonging to the class level ) already exists , so the earlier execution. Find a java book entry look at it
------ For reference only --------------------------- ------------
I finally found the answer :
will be conducted in the following situations class initialization operations:


initialization will call the class's static code block.

Note: The current class

没有评论:

发表评论