When polymorphism meet initialization of an object, what will happen.
Here is a pretty strange but reasonable example.
A piece of code
1 | /** |
Output of the code
Output:
1 | Circle, Before drawing |
Explanation
Dynamic binding of method
Polymorphism, the parent’s method overrided by subclass before the construction of an object.
Construct of a object:
execute a
sizeof()
like operation to determine the memory needed, the set the allocated memory to ZERO.Here is the size of ColorfulCircle, containing field ‘color’.
Go upward to Object.class, then go down according the inherit level. Execute every class’s constructor to make the object more specific.
Here, the inherit level is Object -> Circle -> ColorfulCircle, so make the allocated memory a Object first, then Circle, finally ColorfulCircle. Each step only do its own affair, other fileds owner by more specific classes will remain uninitialized(ZEROS, that is null for objects, 0 for numbers, false for boolean etc).