0
public class Tmp {
    public static void main(String[] s) {
        //new Tmp(); //comment 1
    }
    A a = new A(1); //comment 2
}

class A {
    A(int i) {
        System.out.println("value in A: " + i);
    }
}

I assumed the object a was created after the line with comment 2 was executed. But nothing was printed. Only after enabling the line with comment 1, "value in A: 1" is printed. Then I am confused that when the object is really created? In contrast, static A a = new A(1); will print "value in A: 1" even with the line with comment 1 disabled.

Can anyone explain the mechnism behind this? Thanks.

xin
  • 309
  • 2
  • 19

1 Answers1

5

A a is a field of the enclosing class.

(non static) fields get initialized when you instantiate an object of that class. Your a field is thus "filled" only when a new Tmp() takes place.

That is all there is to this.

Clijsters
  • 4,031
  • 1
  • 27
  • 37
GhostCat
  • 137,827
  • 25
  • 176
  • 248