解决的办法
1.放在构造代码块中
public class Regist2 {
Person[] per = new Person[10];
//因为在类中方法外,只能定义成员变量和其他方法,而不能进行对这个类成员的操作,包括修改变量。所以就需要用到构造代码块
{
per[0] = new Person();
per[0].username = "wy";
per[0].password = "wy";
}
2.放在构造方法中或者main函数中
public Regist2() {
per[0] = new Person();
per[0].username = "wy";
per[0].password = "wy";
}
构造代码块{},在类中方法外,每次创建对象都会调用一次构造方法,构造代码块优先与构造函数执行。
以上两个场景都是利用了构造代码块的两个特性:
1.在每个构造函数中都运行(因为在实例化对象的时候构造代码块优先于构造函数加载)
2.在构造函数中它会首先运行