问题描述
我是 Java 新手,遇到以下情况的错误:
I am new to Java and getting an error for the following case:
markerObj = null;
markerObj.sections = RowData[1];
但是,删除第一行后,它工作正常.有什么问题?
But, after removing the first line, it works fine.What is the issue?
推荐答案
变量名只是引用.它们指向包含对象的内存空间(在堆中).
Variable names are only references. They point to a space in memory (in the heap) which contains an object.
当您执行 MyObj myObject = new MyObj();
时,它会做两件事:在内存中创建对象,并将 myObject 引用指向它.因此,当您执行 myObject.sections
时,它会遵循引用,并检查内存中对象的部分.
When you do MyObj myObject = new MyObj();
, it does two things: create the object in memory, and point the myObject reference to it.So when you do myObject.sections
, it follows the reference, and check the sections part of your object in memory.
然后当您执行 myObject = null
时,您基本上会破坏您的引用和内存中的对象之间的链接.因此,在执行 myObject.sections
时,Java 无法再跟踪引用,因为它没有指向任何内容.所以它抛出一个 NullPointerException
Then when you do myObject = null
, you basically destroy the link between your reference and your object in memory. Hence when doing myObject.sections
, Java cannot follow the reference anymore because it's not pointing to anything. So it throws a NullPointerException
注意对象本身没有被myObject = null
销毁,只有引用被取消.垃圾收集器然后检测到您的对象无法访问(如果没有其他引用)并回收内存,销毁该对象.
Note that the object itself is not destroyed by myObject = null
, only the reference is nullified. The Garbage Collector then detects that your object is unreachable (if there's no other reference to it) and reclaims the memory, destroying the object.
这篇关于声明对象为空后为成员变量赋值时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!