I have created an upcasting demo and i don't understand how this code is working or i can more specifically say why is constructor of base class also called while the dispatching is done with the Derived class.And there is even not a call to the constructor of the base class.I haven't even used super keyword anywhere than how is the constructor of the base class also called.
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;
}
}
class Test{
public static void main(String args[]){
Base b=new Derived();
System.out.println(b.getValue());
}
}
When you create a new Derived
object, its constructor will be called. Since Derived
has a superclass Base
, its construtor will be called first. In the constructor, the overridden method addValue
will be called, which leads to the temporary value of 20. After that, addValue
of Derived
is called and adds another 20 to value
. The final result is 40.
Since, you did not call the constructor of the superclass using super
yourself, Java will do that automatically:
Derived() {
super();
addValue();
}