David Gillette wrote:. . . the code was intentionally written to be confusing . . .
Too true. Cert exam revision books often use such confusing code. OP: please always tell us
where such code comes from. Also please explain why there are line numbers
n1,
n2,
etc.
There are many problems with the way it is written . . .
Too true. I can see three serious design problems:-
1: Overridable (instance) method called from constructor.2: Method with same name as constructor.3: Superclass and subclass with fields with the same identifier (=name).But as DG said, they like confusing code.
Remember that field declarations are
not polymorphic.
My suspicion is --id evaluates to -1 because at the time when the variable is used it hasn't been initialized. . . .
I am sure you are correct.
1: Variable declared as Base: Base class loaded.2: Variable initialised as Derived.3: Derived constructor starts by calling its superclass' constructor.4: Base constructor calls Object constructor.5: Look up the order of initialisation in the Java® Language Specification (=JLS) to see when field initialisation occurs.6: Base() method called: this is polymorphic, so it calls the version in the runtime type, i.e. Derived.7: Base() method decrements and prints value of field in subclass object.8: Control returns to subclass object and initialisation of fields in subclass object occurs.So the value of the field has its default value at the time the method runs. That was before field initialisation. Hence,
voilà −1.
Try changing the declaration to be
final and see what happens. Find the section in the JLS describing the exact order of initialisation of variables when an object is constructed.