Answer the question
In order to leave comments, you need to log in
Why can't initialize the object passed in the function argument?
I am currently writing a Java program using recursion. I will not include the long code itself in the question, but I made a small example showing the essence of the problem.
I created a class with a constructor.
Then I created a class object but didn't initialize it.
The function then calls a recursive function that must initialize this object and pass it as an argument. There is no recursion itself here, because it does not affect the problem.
A recursive function initializes an object. After that, the main object still remains empty. Printing its value throws a null pointer exception. What's wrong, and how to fix it?
public class Test
{
private class Node //создаем сам класс
{
int value;
public Node(int number) //Конструктор
{
value = number;
}
}
public Node root; //Создаём объект
public void assign(int value)
{
assign(value, root); //Передаем этот объект как аргумент
System.out.println(root.value); //Null pointer exception
}
private void assign(int value, Node newNode)
{
newNode = new node(value);//Инициализируем
}
}
newNode==root
Answer the question
In order to leave comments, you need to log in
In Java, arguments are passed by value. Roughly speaking, when the assign method is called, the newNode variable is created in its scope, into which the address of the value of the root field is copied. The new operator allocates a memory area on the heap for an object of the Node class and returns its address to the newNode variable, overwriting the old value in it. After the assign method completes, the newNode variable ceases to exist along with the address written to it, and the root field remains with the null value.
PS The remarks in the other answer are absolutely correct too.
oh, who taught you to write like that? to begin with, all class names with a capital letter should be
private class node //create the class itselfno, you are not creating anything here, but in fact you are describing some kind of structure, object
public node root; //Create an objectno, you are not creating anything here, but only declared a variable
System.out.println(root.value); // Null pointer exceptionwell, of course, root was not created for the current object. And here, in general, in principle, there is no code for its task
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question