在数组中添加不同类型的对象

Adding objects of different types in an Array

我对这段代码有几个问题:

public class 主类 {

public static void main(String _args[]) {
    // this is a reference variable of type Truck, referring
    // an object of type Truck
    Truck _firstTruck = new Truck("Volvo", "Generic", "blue", 8000, 20);

    // this is a reference variable of type Vehicle, referring
    // an object of type Vehicle
    Vehicle _firstVehicle = new Vehicle("Bicycle", "red");

    // since a Truck is also a Vehicle, we can have 
    // a reference variable of type Vehicle, referring
    // an object of type Truck
    Vehicle _secondVehicle = new Truck("Scania", "unknown", "green", 7000, 30);

    //better yet, we can do this:
    Vehicle _vehicles[] = new Vehicle[3];
    _vehicles[0] = _firstTruck; // a truck is a vehicle
    _vehicles[1] = _firstVehicle;
    _vehicles[2] = _secondVehicle;

    for (int i = 0; i < _vehicles.length; i++) {
        _vehicles[i].increaseSpeedBy();
    }

}

}

我知道数组 _vehicles[] 是 Vehicle 类型,因此我无法将 Truck 对象添加到数组中,对吗?

 _vehicles[1] = _firstVehicle;
 _vehicles[2] = _secondVehicle;

这两个没问题,因为它们是同一类型(车辆);

_vehicles[0] = _firstTruck;

是错的那一行。 所以我将创建卡车类型的 _vehicles[0]。

Truck _vehicles[0]=new Truck("","","",0,0);

然后只需添加

_vehicles[0] = _firstTruck;

我的假设好吗?

另外,在老师的笔记中我看到我应该这样做:

_vehicles[0] = new Object();

有人可以解释一下吗?

一个数组只能是一种类型。如果 truck 不是 vehicle 的子 class,您将无法将所有这些对象添加到同一个数组中。但是,如果 class truck "extends" vehicle,您应该能够添加所有这些对象,前提是数组的类型是 vehicle。