在Array中添加不同类型的对象

时间:2016-02-14 16:05:17

标签: java arrays extend

我对此代码有几个问题:

公共类MainClass {

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

}

}

据我所知,Array _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();

有人可以解释一下吗?

1 个答案:

答案 0 :(得分:0)

数组只能是一种类型。如果truck不是车辆的子类,则无法将所有这些对象添加到同一阵列中。但是,如果班级卡车&#34;扩展&#34;如果车辆类型为车辆,您应该能够添加所有这些对象。