Java学习笔记(一)对象数组的初始化

时间:2023-02-26 18:41:15

刚学java,遇到对象数组初始化问题,报错:Exception in thread "main" java.lang.NullPointerException...

题目:有个student类,建立一个student数组,并通过name,email等方式查询。

Student Classmate = new Student[4];
Classmate[0].SetterName("zhangsan");
...

程序编译没问题,执行时在Classmate[0]处报错:Exception in thread "main" java.lang.NullPointerException...

报错原因:Student Classmate = newStudent[4]只是定义了引用变量,还没有初始化。

正确的初始化方法:

Student Classmate = new Student[4];
Student p1 = new Student();
p1.SetterName("zhangsan");
Classmate[0] = p1;

或者

Student[] Classmate = {
            new Student("lisi"),
            new Student("zhangsan"),
            };