Home > database >  Can we call a Arraylist from a class to another class, and can be used by all methods in the 'a
Can we call a Arraylist from a class to another class, and can be used by all methods in the 'a

Time:06-19

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<String> string = 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
}

CodePudding user response:

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/

CodePudding user response:

In your class another, create a new Arraylistclass and assign it to a variable. Then access that arraylist like so

Class another{
var arrlistclass = new ArrayListClass()
//now access it
arrlistclass.string
}

If you meant inheritence, write super.string

CodePudding user response:

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.someList.put ("Foo");    
}

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

  •  Tags:  
  • java
  • Related