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;
}
}