-1
public class TestA {
    static int x;
    static TestA a;
    static TestB b;

    TestA() { x++;}

    static void runTest() {
        a = new TestA();
        b = new TestB();
    }

    public static void main(String[] args) {
        runTest();
        runTest();
        System.out.println(a.x);
        System.out.println(b.x);
        System.out.println(a.x + b.x);
    }
}

class TestB extends TestA {
    static int x;
    TestB(){ x += 2;}
}

The result of this code is : 4 4 8 May I ask why? I tried to understand it by drawing a graph. But it never makes sense. How can x be changed to 4?

Lei Zuo
  • 39
  • 5

1 Answers1

1

When you call new TestA(), the TestA constructor runs.

When you call new TestB(), the TestB constructor and the TestA constructors both run.

The x seen by the TestA constructor is not the same x seen by the TestB constructor. If you change the two constructors to this, they would still do the same:

TestA() { TestA.x++;}

TestB(){ TestB.x += 2;}

Also, using instance variable to access a static field is highly discouraged, so although it's allowed, you should never do it. The compiler replaces the instance variable with the appropriate class for static access, as seen by the compiler. That means your print statements compile to the same as this:

System.out.println(TestA.x);
System.out.println(TestB.x);
System.out.println(TestA.x + TestB.x);

Finally, you call runTest() twice, and each call will execute the TestA constructor twice, and the TestB constructor once, so all in all, you execute the TestA constructor 4 times, and the TestB constructor 2 times.

Result:
4 times TestA.x++ means TestA.x = 4
2 times TestB.x += 2 means TestB.x = 4

That is why the program output is:

4
4
8
Andreas
  • 154,647
  • 11
  • 152
  • 247