public class Base {
int var =0;
Base(){
System.out.println("Inside Base constructor .....");
setVar();
}
public void setVar(){
System.out.println("Inside base setVar method.....");
var+=10;
}
public int getVar(){
return var;
}
}
Derived Class:
public class Derived extends Base {
Derived(){
System.out.println("Inside Derived constructor .....");
setVar();
}
public void setVar(){
System.out.println("Inside Derived setVar method.....");
var+=20;
}
public static void main(String[] args){
Base b = new Derived();
System.out.println(b.getVar());
}
}
Output.....
Inside Base constructor .....
Inside Derived setVar method.....
Inside Derived constructor .....
Inside Derived setVar method.....
40
Question ----> why when control goes to base class constructor , setVar() method of Derived class is called instead of Base class setVar() method. I expected output as 30 , but when ran this program in debug mode found the flow and got output as 40. Could anyone please explain the logic behind this. Thanks
Java will decide which method to run based on the runtime type of the variable, i.e. use polymorphism, at all times, even if the method called is from a base class constructor.
When the base class constructor is called, polymorphism means that the derived class's version of setVar
is called, and 20 is added. Then the derived class constructor is called, and again the derived class's version of setVar
is called, and 20 is added, again, yielding 40.