Zera42
Zera42

Reputation: 2692

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
    }

}

I'm coming from C++ so I've never had this issue before. Normally to access a function I could just go like root->add_comment(root, comment); and it would work just fine, but in java it's giving me a null pointer, do I have to initialize root? Because in the tree class I have an add_comment function which recursively adds a node into the tree.

Upvotes: 0

Views: 131

Answers (4)

AllTooSir
AllTooSir

Reputation: 49432

Your instance variable root is declared but never initialized. So , you are trying to invoke a method root.add_comments(root, comment); on null reference . it is effectively null.add_comments(root, comment); , hence a NullPointerException.

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

You need to initialize it somehow .

protected tree root = new tree(); 

Or pass a new instance of tree in the destination constructor and assign it to the instance variable.

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

This is how you do a null-check in Java :

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

P.S. : Please follow Java's naming conventions.

Upvotes: 5

Ozan Deniz
Ozan Deniz

Reputation: 1087

You need to initialize tree root

tree root  =  new tree();

Upvotes: 0

chessbot
chessbot

Reputation: 436

Yes, you have to initialize root, otherwise it is set to null as you've seen. You can either initialize it in the constructor (i.e.,)

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

or give a default initialization when you declare it.

protected tree root = new tree();

Think of it as a reference to a tree rather than a tree itself.

Upvotes: 0

SJuan76
SJuan76

Reputation: 24895

You never initialize root. Unlike C++, in Java all variables are treated as references / pointers, so no instances are created until a new instruction is processed.

Upvotes: 0

Related Questions