I want to change the object of class Car to an object of class FastCar. It is easy to see that the main method returns an error in this case. I wrote it to be easier to express my question: how can I build an object of a subclass around an object of a superclass? What would be the best way considering that the classes might not be small as in the examples below? The solution should also work for big classes, with a lot of fields.
public class Car {
String name;
String label;
Car(String name){
this.name = name;
label = "Car";
}
Car(){
this("dafaultCarName");
}
}
public class FastCar extends Car{
String howFast;
FastCar(){
howFast = "veryFast";
}
FastCar(String name){
super(name);
howFast = "veryFast";
}
}
public static void main(String[] args) {
FastCar fast;
Car car = new Car("FastCarName");
fast = (FastCar) car;
}
UPDATE
As @Arthur said:
public class Car {
String name;
String label;
Car(String name){
this.name = name;
label = "Car";
}
Car(){
this("dafaultCarName");
}
}
public class FastCar extends Car{
String howFast;
FastCar(){
howFast = "veryFast";
}
FastCar(String name){
super(name);
howFast = "veryFast";
}
FastCar(Car car){
super(car.name);
}
}
public static void main(String[] args) {
FastCar fast;
Car car = new Car("FastCarName");
car.label = "new Label";
fast = new FastCar(car);
System.out.println(fast.label);
}
The constructors from FastCar suggested by @Arthur are not good because the label is not preserved.
The output is Car but I expected it to be new Label.
I want some trick to convert my "car" into a "fast car" without loosing data. Also this trick should also be efficient for larger classes.