删除构造函数内部的List<Person>
before people = …
,否则,您将在构造函数内部声明一个新的局部变量people
,使该字段 成为阴影people
(然后不再使用)。这使类字段未初始化(null
),然后导致NPE。
相反,您想要初始化字段people
:
public Club() {
// you can also use "this.people = …" to be explicit
people = new ArrayList<>();
}
要显示差异:
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
}
}