Hi,
studying for the
SCJP, I had some problems in understanding the rules of the class loading and object creation process. To entirely understand it, I wrote a little
test programm, which imho answers all open questions.
I'd like to share it with you, in the hopes that it will also help you.
(Please let me know what you think...)
The output is:
begin
End variable declaration
------------------------------
static variable A1
static initializer A2
static initializer A3
static initializer A4
static initializer A5
static variable A6
static initializer B1
static variable B2
static initializer B3
static initializer B4
static initializer B5
static variable B6
------------------------------
End static initialization of B
------------------------------
------------------------------
End static initialization of A
------------------------------
instance member A1
instance initializer A2
instance initializer A3
instance initializer A6
instance initializer A7
instance member A8
instance constructor A5
instance constructor A4
instance member B1
instance initializer B2
instance initializer B3
instance initializer B6
instance initializer B7
instance member B8
instance constructor B5
instance constructor B4
------------------------------
End instance creation of B
------------------------------
instance member A1
instance initializer A2
instance initializer A3
instance initializer A6
instance initializer A7
instance member A8
instance constructor A5
instance constructor A4
------------------------------
End instance creation of A
------------------------------
From the output I come to the following conclusions:
1. A class is loaded only when it's used, not just because it's part of the file where the main method is executed.
2. A class is loaded, as soon as an instance is is created, or if you access a static member of the class.
3. You have to look at the process in different levels of abstraction.
First level: The classes - Parent class is loaded before child class
Second level: The variables and initializers - static before instance, each "group" from top to bottom, first in class is loaded first
Third level: The constructors - The last thing beeing called are the constructors. The order in which they are called depends on how they are chained.
4. static variables / initializers are loaded only once, instances variables / initializers are loaded once for each instance created.
It's as easy as this. That's imho all you got to know!
Reading the SCJP book of Kathy and Bert, so far I never understood it in this detail, and failed in all mock test on the subject.
Now with some coding, I think I finally understood.
Did I get it right???
Marcus
[ October 18, 2008: Message edited by: Marcus Moreno ]