1

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?

Sum
  • 25
  • 2

2 Answers2

0

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();
Eran
  • 387,369
  • 54
  • 702
  • 768
0
Vehicle v = new Vehicle("Dummy"); 
//First object create with following properties,
name = "Dummy"
tyres = 0

v = new TwoWheeler(); 
//Second object created with following properties,

 /*   Flow goes like,
    TwoWheeler() constructor called,
    flow again go up to super and assign name with "default",
    while flow come back to TwoWheeler() constructor ,
    tyres = 2 assign.
 */

Finally, output comes as per you have displayed. and into

Vishal Gajera
  • 4,137
  • 5
  • 28
  • 55