To understand downcasting, I did the following code.
class Vehicle{
protected int tyres=0;
protected String name="default";
Vehicle(){
}
Vehicle(String aname){
name=aname;
}
//abstract void setTyres(int number);
public void print(){
System.out.println(name+":"+tyres);
}
}
class TwoWheeler extends Vehicle{
TwoWheeler(){
tyres=2;
}
public void print(){
System.out.println(name+":"+tyres);
}
}
class FourWheeler extends Vehicle{
FourWheeler(){
tyres=4;
}
public void print(){
System.out.println(name+":"+tyres);
}
}
public class vehicles {
public static void main(String[] args) {
try{
Vehicle v= new Vehicle("Dummy");
v.print();
v= new TwoWheeler();
v.print();
}
catch(Exception e){
System.out.println(e.toString());
}
}
}
Now the output is Dummy:0 default:2
while I expected Dummy:0 Dummy:2 Looks like the parent constructor is called a second time? Please explain what happens here. Also, How do I do the downcasting without the parent being called?