簡體   English   中英

嘗試調用對象的函數時,java中的NullPointerException

[英]NullPointerException in java while trying to call a function of an object

public abstract class destination{

    //Here are the data that are common in each of the 'File Types'
    protected tree root;
    //constructor that will call the correct constructor when a derived children is made.
    public destination()
    {
        super();        //Will call the other constructors
    }
    public void get_info()
    {
    }
    public void print()
    {

    }
    public void add_comment(String comment)
    {
           root.add_comments(root, comment); //null pointer exception
    }

}

我來自C ++,所以以前從未遇到過此問題。 通常,要訪問一個函數,我可以像root-> add_comment(root,comment); 並且它可以正常工作,但是在Java中,它為我提供了一個空指針,我是否必須初始化root? 因為在樹類中,我具有add_comment函數,該函數以遞歸方式將節點添加到樹中。

您的實例變量root已聲明,但從未初始化。 因此,您正在嘗試調用方法root.add_comments(root, comment); null引用上。 實際上是null.add_comments(root, comment); ,因此為NullPointerException。

protected tree root; // is declared , never initialized.

您需要以某種方式對其進行初始化。

protected tree root = new tree(); 

或在destination構造函數中傳遞tree的新實例,並將其分配給實例變量。

public destination(tree root)
{
    super();        
    this.root = root;
}

這是在Java中執行空檢查的方式:

if(root!=null) { // lowercase "null"
     root.add_comments(root, comment);
}

PS:請遵循Java的命名約定

您永遠不會初始化root 與C ++不同,在Java中,所有變量都被視為引用/指針,因此在處理new指令之前不會創建任何實例。

是的,您必須初始化root ,否則如您所見將其設置為null 您可以在構造函數中對其進行初始化(即)

public destination()
{
    super();
    root = new tree();
}

或在聲明時提供默認的初始化。

protected tree root = new tree();

可以將其視為對樹的引用,而不是對樹本身的引用。

您需要初始化tree root

tree root  =  new tree();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM