Forums Register Login

Initialization blocks...

+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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 ]
+Pie Number of slices to send: Send
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 ]
+Pie Number of slices to send: Send
The following link might help.
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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
We can walk to school together. And we can both read this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 978 times.
Similar Threads
code called before constructor
Question on static
Initialisation blocks
Blocks
Please explain the output
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 02:36:45.