2012-10-27 36 views
0

構造的對象在一個類中的數組列表我有3類: -創建從另一個

Tell - The main program
Item - The individual telephone directory items
Directory - A directory object which stores all the items.


我想要做的就是創建存儲在目錄中的數組列表來自項目類的對象,這是我如何做到這一點。

從訴說,我調用的方法: -

Directory.add(name, telNo); 

目錄類別: -

public class Directory 
{ 
    ArrayList<Entry> entries = new ArrayList<Entry>(); 
    // Add an entry to theDirectory 
    public static void add(String name, String telNo)  
    { 
     entries.add(new Entry(name, telNo)); 
    } 
} 

項類: -

public class Entry 
{ 
    String name; 
    String telNo; 
    public TelEntry(String aName, String aTelNo) 
    { 
     setNumber(aTelNo); 
     setName(aName); 
    } 

    private void setNumber(String aTelNo) 
    { 
     telNo = aTelNo; 
    } 
    private void setName(String aName) 
    { 
     name = aName; 
    } 

} 

然而,我的程序不編譯,它顯示此錯誤: -

"non-static variable entries cannot be referenced from a static context" 

任何人都可以解釋我做錯了什麼?

回答

2

您必須聲明你的ArrayListDirectory類爲靜態,因爲你正在使用它從靜態上下文 - 你add方法。而且你也可以使它成爲private,因爲你的字段應該是私密的,並且提供一個public訪問器方法來訪問它。

private static ArrayList<Entry> entries = new ArrayList<Entry>(); 

您只能從靜態上下文訪問靜態變量。因爲非靜態變量需要使用類的實例,並且在靜態上下文中沒有可用的實例,所以不能使用它們。

2

聲明entriesstatic。您只能訪問靜態上下文中的靜態變量。

static ArrayList<Entry> entries = new ArrayList<Entry>();