问题遇到的现象和发生背景
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;
运行正常
我想要达到的结果
我想明白:为什么只是等号两遍的引用调换位置就会发生空指针异常?