简体   繁体   中英

How do Java classes get information from the Entry class?

So lets say that in my entry point class (ie the class which runs when the program starts (which has the public static void main(String args[]) function). In that class I have this variable:

private ArrayList<String> myData=new ArrayList<String>();

This class instantiates another class, which needs to have access to the myData member of the entry point class. How can it retrieve this arraylist?

Edit: To clarify, in the main() method I could do this:

SomeOtherClass myClass=new SomeOtherClass();

and then I could do:

myClass.someMethod();

however, in the myClass object, how could I perform a method/retrieve something from the entry class, which instantiated the myClass object?

The best way to give the class you instantiate access to myData would be to pass it into the constructor when it is created.

Then, in your constructor, you can save the ArrayList into a member variable of the class.

For example, your object constructor will look like:

private ArrayList<String> myData;

public YourObjConstructor(ArrayList<String> data){
    myData = data;
}

It sounds like your entry point is still static when it calls some other class, but your ArrayList is a member of an instance of it. You need to move out of the static world and into instances.

I'd refactor your main method into a private construtor, and put in a new main() which launches it as a new instance.

Note that this code is very rough, but it should serve to illustrate what you need to do.

public class EntryPoint {
    private ArrayList<String> myData=new ArrayList<String>();

    public static void main( String[] args ) {
        EntryPoint ep = new EntryPoint();
        ep.init();
    }

    private void init() {
        // Populate myData perhaps?

        SomeOtherClass myClass=new SomeOtherClass();
        myClass.someMethod( this );
    }

    public List<String> getMyData() {
        return myData;
    }
}   

public class SomeOtherClass {
    public void someMethod( EntryPoint entry ) {
        List<String> data = entry.getMyData();
        // do stuff with data..!
    }
}

The class containing main() is just an ordinary class. In your case, you'd have to make myData public and possibly static (or, of course, add an accessor). Just like you'd do with any other class.

You could also pass an Entry object to the other class, like this:

public static void main(String[] args) {
    Entry entry = new Entry();
    SomeOtherClass myClass=new SomeOtherClass(entry);
    // continue as before
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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