I am trying to add newly created objects to an ArrayList in the constructor of a class. The new objects are being created in another class in the main method.
Main method:
public static void main(String[] args) {
// TODO code application logic here
Player p1 = new Player("Peter");
}
My Player class:
public class Player {
protected static int age;
protected static String name;
protected static ArrayList players = new ArrayList();
Player(String aName) {
name = aName;
age = 15;
players.add(new Player()); // i know this doesn't work but trying along these lines
}
}
nameandageshould not be static.players.add(this)which refers to your current instance, but I my suggestion would be to revise your structure because I think it should not be the Player's duty to remember which players have been created so far. This functionality should be delegated to a dedicated entityArrayListinstead ofPlayer previous;Player nextI would bet that there will be a methodnext&previous. Otherwise I agree with @Grove that it should be delegated elsewhere