Remove the List<Person>
before people = …
inside the constructor, otherwise you are declaring a new local variable people
inside the constructor shadowing the field people
(which is then never used). This leaves the class field uninitialized (null
) and then causes the NPE.
What you want instead is initializing the field people
:
public Club() {
// you can also use "this.people = …" to be explicit
people = new ArrayList<>();
}
To show the difference:
class Example {
private int myNumber;
public Example() {
myNumber = 42; // sets the field of the class
int myNumber = 1337; // declares a new local variable shadowing the class field
myNumber = -13; // accesses the object in the closest scope which is the local variable
this.myNumber = 0; // explicitly accesses the class field
}
}