我想将类Car的对象更改为类FastCar的对象。很容易看出在这种情况下main方法会返回错误。我写它是为了更容易表达我的问题:如何围绕超类的对象构建子类的对象?考虑到类可能不会像下面的示例中那样小,最好的方法是什么?该解决方案也应适用于具有许多领域的大型课程。

    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;
    }


更新
正如@Arthur所说:

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);
    }


@Arthur建议的FastCar中的构造函数不好,因为标签未保留。
输出是Car,但我希望它是new Label
我想要一些技巧,可以在不丢失数据的情况下将我的“汽车”转换为“快速汽车”。同样,此技巧对于较大的类也应该有效。

最佳答案

向下转换有几种方法:


FastCar(Car car)类中添加构造函数FastCar
public FastCar asFastCar()类中引入方法Car
在任何地方引入util方法public static FastCar castToFastCar(Car car)

09-12 22:46