我有 3 节课:-
<小时/>Tell - The main program
Item - The individual telephone directory items
Directory - A directory object which stores all the items.
我想要做的是在目录中创建一个数组列表,用于存储项目类中的对象,这就是我正在做的事情。
来自 Tell, 我正在调用方法:-
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"
谁能解释一下我做错了什么?
最佳答案
您需要将 Directory
类中的ArrayList声明为静态,因为您是从静态上下文使用它 - 您的add
方法。您还可以将其设置为私有(private)
,因为您的字段应该是私有(private)的,并提供一个public
访问器方法来访问它。
private static ArrayList<Entry> entries = new ArrayList<Entry>();
您只能从静态上下文访问静态变量。因为,非静态变量需要您的类的实例才能使用,而静态上下文中没有可用的实例,因此您无法使用它们。
关于java - 从一个类中构造的对象在另一个类中创建数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13100541/