0基础自学java中,在学习对象的创建与应用时遇到该问题.
代码中的引用类型: Student,Pc
public class A {
public static void main(String[] args) {
//实例化一个 "学生A"
Student studentA = new Student();
//实例化ac,指向学生A的电脑
Pc ac =new Pc();
ac = studentA.computer;
//为学生A的电脑的型号赋值
studentA.computer.model="asdf";
//ac指向studentA.computer.brand,并赋值
ac.brand = "HP";
//ac指向studentA.computer.color,并赋值
ac.color = "white";
//输出结果
System.out.println(studentA.name ="qwe");
System.out.println(studentA.code = 114514);
System.out.println("A学生电脑的品牌为" + ac.brand);
System.out.println("A学生电脑的型号为" + studentA.computer.model);
System.out.println("A学生电脑的颜色为" + studentA.computer.color);
}
}
空指针报错
报错内容:
Exception in thread "main" java.lang.NullPointerException: Cannot assign field "model" because "studentA.computer" is null
at A.main(A.java:12)
实例化ac时将
ac = studentA.computer;
替换为
studentA.computer = ac;
运行正常
我想明白:为什么只是等号两遍的引用调换位置就会发生空指针异常?
1、ac = studentA.computer;是将studentA.computer赋值给ac,而studentA.computer在创建studentA的时候并没有实例化是空的,所以在调用studentA.computer.model="asdf";时会报空指针异常,也就是说只要studentA.computer是空的,那么只要调用其属性或者方法都会报空指针异常,因为程序不能找到是谁调的。
2、studentA.computer = ac;是将ac赋值给studentA.computer,ac是new出来的一个新对象,其不是空的,所以将ac赋值给studentA.computer之后,studentA.computer也不是空的,此时调用其属性和方法是正常的,也就不会报错了。
ac = studentA.computer;
简单理解就是此时 ac已经new出内容来了,computer还只是一个名字,没有具体内容。
ac = studentA.computer你的这个studentA.computer是空的,还没new一个对象,也没有赋值给studentA.computer,倒过来是对了的, studentA.computer = ac
报错的位置应该是studentA.computer.model="asdf"
,前面的代码改成ac = studentA.computer;后,studentA.computer的值依然为null,所以会报空指针异常