I am testing some polymorphism in java and my code looks like the following:
class Base {
int value = 0;
public Base(){
System.out.println("Came Here And Value is: " + value);
addValue();
}
String addValue(){
System.out.println("Calling Bases' addValue and value is currently: " + value);
value += 10;
return "";
}
int getValue(){
return value;
}
}
class Derived extends Base{
public Derived(){
System.out.println("Calling Derived constructor and value currently is: " + value);
addValue();
}
String addValue(){
System.out.println("Came to Deriveds' addValue and value now is: " + value);
value += 20;
return "";
}
int getValue(){
return value;
}
}
public class MyClass {
public static void main(String [] args){
Base b = new Derived();
System.out.println(b.getValue());
}
}
So the thing here is, it prints 40 but I'm guessing that it should print 30. My thoughts are: new Derived first calls new Base, which calls addValue()
and (as addValue()
defined in Base adds up value by 10) value should be 10 at that time. then, Derived's addValue()
is called which makes value 30 (because addValue()
defined in Derived adds value up by 20). But instead, Base invokes it's child's addValue()
. Can someone explain what's happening?