I have a two simple Java classes and I am trying to understand more about cloning and how to cast between different levels of classes. This is the superclass Vehicle.
public class Vehicle implements Cloneable
{
public int x;
public Vehicle(int y) {
x = y;
}
@Override public Object clone() {
Object result = new Vehicle(this.x);
// Location "A"
return result;
}
}
And this is the subclass Truck
public class Truck extends Vehicle
{
private int y;
public Truck(int z) {
super(z);
y = z;
}
@Override public Object clone() {
Object result = super.clone();
System.out.println(result.getClass());
((Truck) result).y = this.y;
return result;
}
}
I am trying to get a copy of Truck while using the superclass to clone but having issues with downcasting not being allowed. I am not really sure how to fix this or where the error is.
I would like to have: Truck a = new Truck(1) and Truck b = a.clone() become the same object.