Is this expected Java behavior?
Yes.
What could cause this?
Your invocation of non-final overridden method in non-final super class constructor.
Let’s see what happens step-by-step:
- You create an instance of
B
. B()
calls super class constructor –A()
, to initialize the super class members.A()
now invokes a non-final method which is overridden inB
class, as a part of initialization.- Since the instance in the context is of
B
class, the methodload()
invoked is ofB
class. load()
initializes theB
class instance field –testString
.- The super class constructor finishes job, and returns (Assuming chaining of constructor till
Object
class have been finished) - The
B()
constructor starts executing further, initializing it’s own member. - Now, as a part of initilization process,
B
overwrites the previous written value intestString
, and re-initializes it tonull
.
Moral: Never call a non-final public method of a non-final class in it’s constructor.