I have 2 pieces of code from Java:
class Test1 {
index = 1;
int index;
}
versus
class Test2 {
{ index = 1; }
int index;
}
the first one failed when compiling, I guess it's because the member "index" is used before it is defined? The second one is error-free. I don't understand why. Can you guys spare some minutes and help me? Thanks a lot!
The second one compiles, because that { ... } inner construction present in the second code is a so-called initializer block. This block is copied into each constructor by Java compiler.
And, as any other class method, it can use a property defined in that class; it shouldn't matter where exactly this property is defined - above or before this block.
The first one does not compile, because it simply does not fit into the language specification for class bodies and member declarations, which defines basically seven allowed things:
class Test2 {
{ index = 1; }
int index;
}
In the above code { index = 1; } is known as Instance initializer block, which is used to intialize the instance variables of the class as static initializer block does for static variables of the class.
Java Compiler will copy this block into every constructor, making it easy for every constructor to share this block of code......
So irrespective of the placement of instance variable in the class, (ie. before or after) the Instance initializer block, it still can be accessed.
See this link:
http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With