| Author |
Initialization blocks...
|
Dan Silva
Ranch Hand
Joined: Sep 05, 2007
Posts: 86
|
|
|
I'm having trouble understanding what initialization blocks are. I feel pretty dumb, but if somebody could give me a brief rundown, it would be much appreciated.
|
 |
Vishwanath Krishnamurthi
Ranch Hand
Joined: Jun 04, 2007
Posts: 331
|
|
Hi Dan, Consider this: For a static init block.. O/P==> one [printed when class is loaded] Now two instantiations: O/P==>one [means its executed only once] ===================== For a init block: O/P==> nothing.... [No instantiations... so no o/p] O/P==> One One [Two instantiations, so its run twice... meaning its run every time an instantiation takes place] [ January 14, 2008: Message edited by: Vishwanath Murthi ]
|
Blog
|
 |
Vishwanath Krishnamurthi
Ranch Hand
Joined: Jun 04, 2007
Posts: 331
|
|
and to keep building on that... The order is as follows.. 1)static init blocks of the superclass are run first, then the subclass's.... 2)In a class a static init block can appear at the top/bottom/anywhere 3)They are run in top-down order... ===== Then if you have done any instantiations for each instantiation 1)the initializations as in class A{ private int aa=10;} 2)init blocks(I mean non static init blocks) of the superclass, then the subclass.... 3)init blocks too in the same top-down order.... ===== then constructors... [ January 14, 2008: Message edited by: Vishwanath Murthi ]
|
 |
Dean Jones
Ranch Hand
Joined: Dec 29, 2007
Posts: 129
|
|
|
The following link might help.
|
 |
Sunny Jain
Ranch Hand
Joined: Jul 23, 2007
Posts: 433
|
|
Let me try to add something :
consider a Superclass, with one static block, one init block , one instance variable conisder one subclass with same
when you create an instance of Subclass, Following hirerachy is followed : 0) Static block of super class executes 1) Static block of Subclass executes 2) Inside constructor of subclass 3) call to super constructor 5) call of Object Class constructor 6) init blocks of super class executes,in the order in which they appear 7) Instance Variable of super class executes 8)Super class constructor executes 9) Init blocks of subclass executes, in the order in which they appear 10) Instance Variable of Subclass are initialized 11) Subclass constructor executes
|
Thanks and Regards,
SCJP 1.5 (90%), SCWCD 1.5 (85%), The Jovial Java, java.util.concurrent tutorial
|
 |
Gitesh Ramchandani
Ranch Hand
Joined: Feb 28, 2007
Posts: 274
|
|
Just to add to the above, what I found is that: 1. static instances & init blocks run (from top to bottom order) 2. instance & init blocks runs (from top to bottom order) 3. constructor runs The above I have tried on a single class. (having no super/sub class) code example: output: Regards, Gitesh
|
 |
 |
|
|
subject: Initialization blocks...
|
|
|