public class Class1 {
List<Class3> allData = new ArrayList<Class3>();
public void setAllData(List<Class3> allData) {
this.allData = allData;
}
public List<Class3> getAllData() {
return allData;
}
}
I have a class which name is Class2 in different package but in the same project with Class1 . How I reach to "allData" from Class1 to use in Class2 ? With getter and setter ? Or any alternative way ?
How I reach to "allData" from Class2? With getter and setter? Or any alternative way?
yes, you should use public
getter/setter. The only alternative way is to use reflection (or make allData
public, which is not recommended too - brokes encapsulation ).
Your allData
field is package-private
, so you can't directly reach it from class Class2
which is placed in another package
You can reach private fields with public getter and setter methods.
You have to make a public getter method in Class2. Then you can call that method in the other classes.
From the other class you first have to instantiate an Class1 object.
Class1 c1 = new Class1()
Then you can access allData
using the getters and setters.
List<Class3> allData = c1.getAllData();
List<Class3> newAllData = new ArrayList<Class3>();
c1.setAllData(newAllData);
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.