Wink Saville’s Blog

January 2, 2008

Java - class instance variable initialization

Filed under: java, programming — wink @ 5:37 pm

Been a few days, had a nice Christmas and New Years. Did work on Android and made good steady progress and nothing real interesting to report until today.

What was interesting is that I leaned that instance variables of class are initialized twice. The first time is before the constructor gets called the variables are initialized to the expected “zero” type defaults. boolean = false, byte/char/short/int = 0, float/double = 0.0 and object references to null.

Next the constructor is called and as the first instruction of the constructors executes values are at there defaults NOT any specific initialization, so don’t assume as I did. Usually this isn’t a problem but if you have inheritance thing can be surprising. In the example below when you instantiate X (new X()) we see:

X#overrideMe(): m=0
X#X(): m=4;

I would have naively expected both to print m=4!

    class B {
B() {
overrideMe();
}

void overrideMe() {
System.out.printf(”Not called\n”);
}
}

class X extends B {
X() {
System.out.printf(”X#X(): m=%d\n”, m);
}

@Override
void overrideMe() {
System.out.printf(”X#overrideMe(): m=%d\n”, m);
}

int m = 4;
}

What happens is that X#overrideMe is called while in the B#B() and m has only its default value zero and it doesn’t acquire its initialized value until after B#B() has completed.

« Older Posts

Powered by WordPress