Reputation: 35
I have a question, I am creating a class, and in my class, i have some variables that i want just to be assigned once, but i would like multiple instances of the class. Example:
public class UserHandler{
private ArrayList<String> users = new ArrayList<String>();
public void addUser(String user) {
users.add(user)
}
}
This is just some example code. Would the ArrayList be instantiated multiple times, or just once, if i create multiple instances of the class?
Upvotes: 0
Views: 505
Reputation: 26926
If the array is declared as
private ArrayList<String> users = new ArrayList<String>();
it will be created once for each instance of UserHandler.
If you change the declaration to static
private static ArrayList<String> users = new ArrayList<String>();
it will be created only once and shared between different instances.
You can find more about class members (static
keyword) here on the tutorial of Oracle:
static
keyword to create fields and methods that belong to the class, rather than to an instance of the class.
Upvotes: 2