import java.util.ArrayList;
public class Team {
private String name;
private ArrayList<Player> team;
public Team(String name) {
this.name = name;
//how come i have to initialize it here in the constructor to see the full list?
this.team = new ArrayList<Player>();
}
public void addPlayer(Player player) {
//why can't i initialize it here in the method, this gives me a list of only recent add?
//this.team = new ArrayList<Player>();
this.team.add(player);
}
public void printPlayers() {
for(Player players : this.team) {
System.out.println(players);
}
}
public String getName() { return this.name; }
}
this.team = new ArrayList<Player>()
have to be in the constructor?this.team = new ArrayList<Player>()
initialized in the method?private ArrayList<Player> team = new ArrayList<Player>();
before the constructor?Answering just the question:
Also what's the difference of having it initialized as
private ArrayList<Player> team = new ArrayList<Player>();
before the constructor?
Nothing, aside from the fact that team
would be initialized before name
.
Field initializers are syntactic sugar for instance initializers. So this:
private ArrayList<Player> team = new ArrayList<Player>();
is identical to this:
private ArrayList<Player> team;
{
// This is an instance initializer.
team = new ArrayList<Player>();
}
and instance initializers are gathered together and inserted into every constructor which invokes (implicitly or explicily) super
, in between the call to super
and the rest of the constructor body. So this:
public class Team {
private ArrayList<Player> team = new ArrayList<>();
public Team(String name) {
this.name = name;
}
}
is identical to:
public class Team {
private ArrayList<Player> team;
public Team(String name) {
super();
this.team = new ArrayList<>();
this.name = name;
}
}