0

Instance initialization blocks execute in the order in which they are defined. Why, then, does the code below have errors where indicated?

public class MyTest {
    public static void main(String[] args) {
    Tester t = new Tester();
    }
}

class Tester {
   { int x; }  // Instance initializer 1 
   { x = 3; }  // Instance initializer 2...ERROR cannot resolve symbol 'x'

   Tester() {  // Constructor
       x = 5;  // ERROR cannot resolve symbol 'x'
 }
}

I thought the compiler just forklifted the instance initializers into the beginning of the constructor. If that's the case, both of these seem like they should work?

1 Answers1

1

Because x is not declared as a class member anywhere. You declare it as a local variable in the first instance initializer block, but the second block doesn't "know" this local variable. The constructor had the same problem, x is not defined...

Try like this:

class Tester {
   private int x;
   { x = 3; }  // Instance initializer 1...

   Tester() {  // Constructor
       x = 5;
 }
}
Amit
  • 45,440
  • 9
  • 78
  • 110
  • Ohhh....right, once the compiler moves the instance initialization block into the constructor, 'x' becomes a variable local to the constructor's scope....got it. Thanks! –  Feb 21 '16 at 19:02