Search code examples
javadowncast

Downcasting excecuting parent constructor again in Java?


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?


Solution

  • The parent constructor is called a second time because you are creating two objects.

        Vehicle v = new Vehicle("Dummy"); // first object created here
        v.print();
        v = new TwoWheeler(); // second object created here
    

    You can't change the type of a base class instance (such as the first object you create) to a sub-class instance.

    What you can do is define a TwoWheeler constructor that accepts a Vehicle argument and initialized the new instance with the properties of the passed Vehicle. This is called a copy constructor.

    TwoWheeler(Vehicle source) {
        super (source.getName());
        tyres=2;
    }
    

    And your main will look like this :

        Vehicle v = new Vehicle("Dummy");
        v.print();
        v = new TwoWheeler(v);
        v.print();