简体   繁体   English

从另一个类中构造的对象在一个类中创建数组列表

[英]Creating an array list in one class from objects constructed in another

I have 3 classes : - 我有3节课:-

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. 我想要做的是在目录中创建一个数组列表,该列表存储来自item类的对象,这就是我的做法。

From Tell, I'm invoking method as: - 从Tell,我将方法调用为:-

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 Directory class as static since you are using it from a static context - your add method. 您需要在Directory类中将ArrayList声明为静态的,因为您是从静态上下文 (即add方法)中使用它的。 And also you can make it private , as your fields should be private, and provide a public accessor method to access it. 并且您还可以将其设为private ,因为您的字段应该是私有的,并提供public访问器方法来访问它。

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. 因为非静态变量需要使用您的类的实例,并且静态上下文中没有可用的实例,所以您不能使用它们。

Declare entries static . entries声明为static You can access only static variables inside static context. 您只能在静态上下文中访问静态变量。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM