[Solved] Java- Overloading and Overriding Concept


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:

  1. When you create a new Derived object, the field value in the Base part is first initialized to 0.
  2. Then the constructor of the superclass Base is called. This calls the add() method.
  3. The add() method is overridden, so the version in class Derived is called, which adds 20 to value; so value is now 20.
  4. Then the constructor of Derived is called. This calls the add() method again.
  5. Again, the add() in class Derived is called, which adds 20 to value.
  6. The result is that value contains the value 40.

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