I have 3 classes : –
Tell – The main program
Item – The individual telephone directory items
Directory – A directory object which stores all the items.
What I’m trying to do is create an array list within directory which stores the objects from the item class and this is how I’m doing it.
From Tell, I’m invoking method as: –
Directory.add(name, telNo);
Directory Class: –
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));
}
}
Entry Class: –
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;
}
}
However my program does not compile, and it displays this error: –
"non-static variable entries cannot be referenced from a static context"
Can anyone explain what I’m doing wrong?
You need to declare your ArrayList in
Directoryclass as static since you are using it from a static context – youraddmethod. And also you can make itprivate, as your fields should be private, and provide apublicaccessor method to access it.You can only access static variables from a static context. Because, non-static variables need an instance of your class to be used, and there is no instance available in a static context, so you cannot use them.