2016-02-14 82 views
-1

我有幾個關於這個代碼的問題:在數組中添加不同類型的對象

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

} 

}

據我所知,陣列_vehicles []是類型的車輛,因此我無法將卡車對象添加到數組中,對嗎?

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

這兩個都可以,因爲它們屬於同一類型(Vehicle);

_vehicles[0] = _firstTruck; 

是它錯的那一行。 所以我會製作卡車的_vehicles [0]。

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

,然後只需添加

_vehicles[0] = _firstTruck; 

是我的假設好?

而且,在老師的筆記我看到,我應該這樣做:

_vehicles[0] = new Object(); 

有人能解釋一下嗎?

+1

卡車是車輛的一個子類,還是不是?這是關鍵信息。 – paisanco

回答

0

一個數組只能是一種類型。如果卡車不是車輛的子類,則無法將所有這些對象添加到同一個陣列。但是,如果班級卡車「延伸」車輛,則應該能夠添加所有這些提供陣列類型車輛的物件。

+0

是的,你是對的,我創造了班車和擴展班卡車和工作。 –

相關問題