Heres the example code:
<blockquote>
code:
<pre name="code" class="core">
class Animal {
}
class Dog extends Animal {
int collarSize = 3;
{ collarSize = 10; }
public static void main(String[] args) {
new Dog();
}
} </pre>
</blockquote>
And if you compile this and use the java bytecode disassembler javap like so (after you have compiled the Dog class using javac):
<blockquote>
code:
<pre name="code" class="core">
javap -c Dog </pre>
</blockquote>
you get the following output:
<blockquote>
code:
<pre name="code" class="core">
Compiled from "Dog.java"
class Dog extends Animal{
int collarSize;
Dog();
Code:
0: aload_0
1: invokespecial #1; //Method Animal."<init>" : ( )V
4: aload_0
5: iconst_3
6: putfield #2; //Field collarSize:I
9: aload_0
10: bipush 10
12: putfield #2; //Field collarSize:I
15: return
public static void main(java.lang.String[]);
Code:
0: new #3; //class Dog
3: dup
4: invokespecial #4; //Method "<init>" : ( )V
7: pop
8: return
} </pre>
</blockquote>
You can see that in main, new is invoked which kicks off Dog's constructor.
Looking at the bytecode for the Dog constructor, Dog's "this" reference is pushed onto the operand stack and then Animal's constructor is invoked.
Next Dog's "this" reference is again pushed onto the stack. The int value 3 is also pushed onto the operand stack and then putfield assigns 3 to collarSize. The values are then popped from the stack. Finally 10 is assigned to collarSize and Dog's constructor returns.
So in a nutshell, it seems that instance variables are given their assigned values after the call to super() and before the instance init blocks run.
Correct me if I am wrong!
Javap is great to play around with if you have the time and interest.
Hhmm, maybe I have too much time on my hands
Best regards.
K
[ July 16, 2008: Message edited by: Keith Nagle ]
[ July 16, 2008: Message edited by: Keith Nagle ]