Chris Headleand
Chris Headleand

Reputation: 6193

Creating an array list in one class from objects constructed in another

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?

Upvotes: 0

Views: 5519

Answers (2)

Rohit Jain
Rohit Jain

Reputation: 213223

You need to declare your ArrayList in Directory class as static since you are using it from a static context - your add method. And also you can make it private, as your fields should be private, and provide a public accessor method to access it.

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

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.

Upvotes: 2

Amit Deshpande
Amit Deshpande

Reputation: 19185

Declare entries static. You can access only static variables inside static context.

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

Upvotes: 2

Related Questions