2012-10-27 53 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>();