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
Derived
object, the fieldvalue
in theBase
part is first initialized to0
. - Then the constructor of the superclass
Base
is called. This calls theadd()
method. - The
add()
method is overridden, so the version in classDerived
is called, which adds20
tovalue
; sovalue
is now20
. - Then the constructor of
Derived
is called. This calls theadd()
method again. - Again, the
add()
in classDerived
is called, which adds20
tovalue
. - The result is that
value
contains 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