0

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.