The source of this question comes from the Online Udemy Course "Pass the Oracle Certified Associate(OCA): Java SE 8 Programmer I EXAM"
Instructor: Udayan Khattry
Please could someone kindly explain how on earth this program prints -1 when executed?
The Derived1 constructor calls the Base1 constructor.
Base1 initializes its own id field to 1000.
The Base1 constructor calls the Base1() method that's overridden in Derived1.
The Base1() method in Derived1 prints --id. id hasn't been initialized yet, so it prints -1.
The Base1() method returns to the Base1 constructor.
The Base1 constructor returns to the Derived1 constructor.
Derived1 initializes its own id field (which was -1) to 2000.
The Derived1 constructor returns to the main method.
The main method finishes running.
In short, the solution the problem is to realize that the Base1 constructor runs before the Derived1.id field is initialized. Superclass constructors always run before fields in subclasses are initialized.
The lesson is that you must never call overridable methods from constructors.
There is no greater crime than stealing somebody's best friend. I miss you tiny ad: