The following code prints output as 40 instead of 30. I'm not able to figure out the solution. Please help with the code.
class Base {
int value = 0;
Base() {
addValue();
}
void addValue() {
value += 10;
}
int getValue() {
return value;
}
}
class Derived extends Base {
Derived() {
addValue();
}
void addValue() {
value += 20;
}
}
public class Test{
public static void main(String[] args) {
Base b = new Derived();
System.out.println(b.getValue());
}
}
The implicit super reference in Derived
constructor calls Base
constructor which in turn calls method addValue()
in the class Base
results in value variable as 10 and then addValue()
in the Derived
class should add 20 to value 10.
So the final output is 30.
But the code prints 40.