0

Here we have two classes, TestA and TestB.

TestB is a subclass of TestA.

The output of this program is 8, but I don't understand how it reaches this output because from my understanding it makes more sense for it to be 6.

I ran the program and found that whenever TestB is invoked, it visits the constructor of TestA before it executes its own constructor. This doesn't make sense since subclass should not inherit the superclass' constructor.

Can someone explain why this is happening? Thanks!

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 + b.x);
    }
}

class TestB extends TestA {
    static int x;

    TestB(){
        x += 2;
    }
}
potatoguy
  • 5
  • 4
  • The first line of the `TestB` constructor has an implicit call to `super()` (so does `TestA` for that matter). – Elliott Frisch May 15 '17 at 05:35
  • The 2 static 'x' fields _are_ separate. When you call `TestB()` constructor, it also calls the `TestA()` constructor. This means that the `TestA.x` is incremented _4_ times. Learning how to use a debugger would have helped you with this. – Gray May 15 '17 at 05:40
  • Constructors are not inherited in Java. – Lew Bloch May 15 '17 at 06:26

0 Answers0