In an interview I was given the following code:

public abstract class Base {
    public int x = 1;
    public Base() {
        foo();
    }
    public abstract void foo();
}

public class Derived extends Base {
    int x = 2;
    @Override
    public void foo() {
        System.out.println("Derived: "+x);
    }
}

class Main {
    public static void main(String... args) {
        Base base = new Derived();
        base.foo();
    }
}

They asked:

What will be printed?

If we were using C++ I think the code should give a compilation error because when the Derived constructor is called first the constructor of the Base class is called. At this point the foo method doesn't exist.

In addition I know that first the inherited class constructor is called, before all the variables is created.

However in Java we get:

Derived: 0
Derived: 2

Why?

I know that like in C++ Java inheritance is based always on virtual tables, and the constructor of the Base class is called before the constructor of the Derived class.

Edit
Report