[Solved] java. inheritance/polymorphism, quiz error?


Here what’s happening is when you call Base b = new Derived() it first calls Derived() on derived class. Now as Derived class extends Base class every constructor of Derived class internally
calls the default cunstructor of base class, similer to

Derived() {
        super();
        addValue();
    }

which in turns calls the Base(). Now inside Base() addValue() is there. As the instanse is of Derived class the addValue() method is called from the Derived class(Read Overriding and Dynamic Method Dispatcher)
so value becomes value+20= i.e. 20. Then when returning fromm Base() it gets addValue() again inside Derived(). So it again calls addValue() and value of value becomes (20+20).

N.B.: You really need to read a lot about Polymorphism, Dynamic method dispatcher for this.

1

solved java. inheritance/polymorphism, quiz error?