为什么null对象会导致NullPointerException

时间:2016-05-31 21:34:39

标签: java object model-view-controller nullpointerexception null

我目前正致力于在Java FX中制作基本的TextEditor,但我遇到了一些困难。我正在尝试合并MVC开发风格并在使用编辑器时在模型中使用Document类型的任何对象,尽管当我尝试保存内容区域时,当我尝试在文档中设置任何变量时我得到NullPointException初始化为null。它工作正常,设置为新文档虽然会使参数为空...

有关此推理的任何信息都非常感谢!

编辑:

对于模棱两可的抱歉,我的意思是初始化一个我试图设置变量的对象。我把它初始化为null:

Document workingDocument = null 

当我将其更改为:

Document workingDocument = new Document(null, null);

我理解创建新文档在内存方面的作用,但不是简单地将其初始化为null的内容...

2 个答案:

答案 0 :(得分:0)

不是100%肯定你的意思,但如果没有对象 - 你不能在其中设置任何变量 - 因为它不存在。因此,如果它被初始化为null则为空 - 即没有。

如果已实例化一个对象,则可以设置它的成员变量 - 即使其中的变量为null - 因为该对象实际存在。

Null为空。因此,即使变量属于某种类型,如果它被实例化,它也将指向null。

Shoe myShoe; // This is a shoe typ variable
myShoe = new Shoe(); // Now it's pointing to a new shoe object
myShoe = null; // Now it's pointing to null, meaning there is no shoe object there anymore.

答案 1 :(得分:0)

您无法对空值进行操作。唯一可用于空值(我的头顶)的操作是

  1. Nullchecks - if(document==null)
  2. Assignements - document=null
  3. 如果您尝试在NullPointerException值上调用某种方法,则会抛出

    null

    Document doc=new Document();
    doc.toString(); // works just fine
    doc=null;
    doc.toString(); throws NPE. 
    

    您应该熟悉OOP的概念,因为此处广泛使用空值。 您可以在此处查看相关主题What is a NullPointerException, and how do I fix it?

相关问题