简体   繁体   中英

Can we call a Arraylist from a class to another class, and can be used by all methods in the 'another' class? No static - Java

Can we call a protected ArrayList from one class to another class, where it can be used for "all methods" in the 'another' class. for example:

public class ArrayListClass {
protected Arraylist<SomeClass> someClass = new Arraylist<>();
}

Then I want to use the ArrayList in all of the methods in another class

public class another {
private void method1() {
//use the same arraylist here
}
private void method2() {
//use the same arraylist here
} 
public void method3() {
// use the same arraylist here
}

There are multiple approaches you can take. In general, you're trying to pass data/variable from one Class to another.

But since you're using protected access modifier, your options will be limited.

If the 'AnotherClass' is in the same package, you could use inheritance (as has been mentioned in the comments) or you could instantiate a new instance as advised in this answer .

If 'AnotherClass' is in a different package, the only option you have is to use inheritance.

If this doesn't work, consider changing the access modifier.

More info on Protected access modifier: https://www.geeksforgeeks.org/protected-keyword-in-java-with-examples/

Sure, just add access methods to ArrayListClass :

 public class ArrayListClass {
    protected Arraylist<String> string = new Arraylist();
    public getTheList () { return string; }
    // more access methods
 }

In your class Another , create in instance of your ArrayListClass:

public class another {
private ArrayListClass alc;
public another () {       // default constructor 
    alc = new ArrayListClass ();        
}
private void method1() {
    alc.getTheList.add ("Foo");    
}

But, if you do that, you should think about why string is protected in the first place.

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