2013-12-10 38 views
1

雖然添加對象與參考名稱我收到錯誤爲什麼在集合接口中添加對象時,無法使用引用名稱創建對象?

class vechile 
{ 
    void service() 
    { 
     System.out.println("Generic vehicle servicing"); 
    } 
} 

public class mechanic 
{ 
    public static void main(String args[]) 
    { 
     List vehicles = new ArrayList(); 
     vehicles.add(vechile q1=new vechile());// this line is showing error 
     vehicles.add(new vechile()); 
    } 
} 
+2

由於Java語法不允許它,因爲Java設計者認爲它沒有用。 –

+2

請注意,在將來的問題中,如果您使示例代碼遵循正常的命名約定等(所以'Vehicle'而不是'vechile','Mechanic'而不是'mechanic'),這真的很有幫助。 。 –

回答

5

vehicles.add(vechile q1=new vechile());是不允許的。

你可以這樣做

vechile q1= null; 
vehicles.add(q1=new vechile()); 
0

在Java或最當我們添加或把一個元素的數組或列表我們沒有傳遞變量本身,而是對象僅供參考,因此OOP語言這個參考變量是什麼都沒有關係。我們必須創建新的引用類型變量,然後在從列表中獲取對象時將該對象分配給它。

List vehicles = new ArrayList(); 
//vehicles.add(vechile q1=new vechile());// Irrelavent 
vehicles.add(new vechile()); // Reference is added to the list and not the variable 
     or 
vechile q1=new vechile() 
vehicles.add(q1); 

然後當我們從列表中選擇此對象首先,我們必須創建引用類型變量,然後分配對象。

Vehicle v1 = null; 
    v1 = vehicles.get(i) //i is the index for q1. 

因此,它在語法上是不允許在java中。

希望我回答了你的問題

相關問題