本文介绍了在Java中将对象类更改为子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

更新
正如@Arthur所说:

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

@Arthur建议的 FastCar 中的构造方法不好,因为标签未保留.
输出是 Car ,但我希望它是 new 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.

推荐答案

向下转换有几种方法:

  1. FastCar 类中添加构造函数 FastCar(Car car).
  2. Car 类中引入方法 public FastCar asFastCar().
  3. 在任何地方引入util方法公共静态FastCar castToFastCar(Car car).
  1. Add constructor FastCar(Car car) in FastCar class.
  2. Introduce method public FastCar asFastCar() in Car class.
  3. Introduce util method public static FastCar castToFastCar(Car car) anywhere.

这篇关于在Java中将对象类更改为子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 21:18