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中它给了我一个空指针,我必须初始化根?因为在树类中我有一个add_comment函数,递归地将一个节点添加到树中。尝试调用对象的函数时,Java中的NullPointerException
是的,你必须初始化'root'。即使在C++中,您也无法在空引用上调用函数。另外,你似乎误解了继承 - 'super()'将调用Object的构造函数,而不是你的子类。你的子类是否在自己的构造函数中初始化root? –
不,他们不!我刚开始哈哈,谢谢我已经把所有派生超级,并由于某种原因把它放在基类-_- – ZZPLKF
如果你尝试在C++的'NULL'指针'root-> add_comment'你会得到一个段错误。这是类似的情况。 – trutheality