关于创建对象数组
今天学习到一些关于java对象数组创建的知识,所以来分享一下。
假定一个学生类Student,再简单的创建一个方法。
public class Student{
private int age;
private int sno;
private String name;
public void show(){
System.out.println("哈哈哈哈哈");
}
}
get和set方法还有构造方法就不写了。
然后我们分别创建一个学生对象和一个学生对象数组。
public class Test {
public static void main(String[] args) {
Student stu = new Student();
Student[] stuArr = new Student[5];
stu.show();
stuArr[0].show();
}
}
运行结果:
哈哈哈哈哈
Exception in thread "main" java.lang.NullPointerException
at edu.beans.Test.main(Test.java:8)
出现一个空指针异常。也就是stuArr[0]并没有实例化。
我们可以理解为:
对象数组并没有给实例化,还需要自己去实例化才可以。
public class Test {
public static void main(String[] args) {
Student stu = new Student();
Student[] stuArr = new Student[5];
stu.show();
stuArr[0] = new Student();
stuArr[0].show();
}
}
运行结果:
哈哈哈哈哈
哈哈哈哈哈