Error while assigning value to member-variable aft

2019-06-12 11:23发布

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?

6条回答
beautiful°
2楼-- · 2019-06-12 11:28

This is exactly what it should do.
By assigning null to a variable, you explicitly state that it is no longer bound to an instance.

So when you refer to sections in your code, you refer to the sections member of a non-existent instance.

查看更多
劳资没心,怎么记你
3楼-- · 2019-06-12 11:32

you are trying to access the member of a null object.. that is the problem..

if you want a new instance.. then do the following..

markerObj = new objectClassName();
查看更多
forever°为你锁心
4楼-- · 2019-06-12 11:33

Variable names are only references. They point to a space in memory (in the heap) which contains an object.

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.

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

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.

查看更多
一纸荒年 Trace。
5楼-- · 2019-06-12 11:34

If you mark an object null you cannot assign values to its member variables.

查看更多
Rolldiameter
6楼-- · 2019-06-12 11:35

The issue is that once you say markerObj = null it points it memory to null, ie it does not initiate any memory objects to it. So you get a null pointer error.

By the way, if you are trying to instantiate its value as null then try to give its internal data property as null, ex. TextView.setText(null);

Maybe it varies for the class that you are using. Check it out at developer.android.com.

查看更多
我命由我不由天
7楼-- · 2019-06-12 11:38

You assign a value to a field of an object which is referred to by marketObj. However, since markerObj doesn't refer to any object (it is set to null), the assignment can't take place, and you will get a NullPointerException instead. If you don't want the exception to appear, you should first assign an object to marketObj.

查看更多
登录 后发表回答