To find out for yourself what is happening exactly, you could run your code in a debugger and step through it to see what happens step by step.
This is what happens:
- When you create a new
Derivedobject, the fieldvaluein theBasepart is first initialized to0. - Then the constructor of the superclass
Baseis called. This calls theadd()method. - The
add()method is overridden, so the version in classDerivedis called, which adds20tovalue; sovalueis now20. - Then the constructor of
Derivedis called. This calls theadd()method again. - Again, the
add()in classDerivedis called, which adds20tovalue. - The result is that
valuecontains the value40.
Paragraph 12.4 of the Java Language Specification explains the rules of how new objects are initialized, and in what order things happen.
2
solved Java- Overloading and Overriding Concept