matt love wrote:The code below is a variation of a question from the B & S book.
produces:
One3()
assert
Exception in thread "main" java.lang.AssertionError
at p1.One2.<init>(Two.java:9)
at p1.Two.main(Two.java:13)
x is not static.
The initialization block runs before the instance of One2 is created. How could x exist at the time the assert is evaluated?
Thanks.
Matt
All instance variables are actually available during construction -- and you have the responsibility to make sure that you use it correctly. In this case, it looks fine. Initialization of instance variables, along with initialization blocks, are done in the order that they are encountered in source code, so the init block is executed after the variable have been set to zero.
And BTW, if you happen to use it before it has been initialized, the variable will have the default value -- which for primitive ints, is a value of zero.
Henry