0

I am learning about Single Linked List. On line 5 of the example I provide below, is an example of a self referential class being called. I feel an infinite amount is being allocated to next as when the Java compiler evaluates the size of Node, it recursively goes over line 5, to determine how much memory to allocate for Node. What am I misunderstanding about line 5.

Would you be able to explain self referential classes?

How much memory is being allocated to the next variable?

Why is line 5 valid? I thought infinite recursive loops would be invalid.

self referential class

BenSmith
  • 429
  • 1
  • 6
  • 14
  • 1
    Keep in mind that `next` is a _reference_ to the object on the heap and not the actual object itself. – Slaw May 31 '21 at 05:07
  • 2
    There is no _call_ on line 5. There is a declaration that includes a type (Node) and an identifier. Does it create a nested Node? No, not until `setNext()` is called. When that happens, as Slaw pointed out, it is simply a reference to an existing object. – Randy Casburn May 31 '21 at 05:20
  • Imagine a house, that has a piece of paper with an address on it. That piece paper is a _reference_ to another house. Does the first house need to be infinitely big in order to store this piece of paper? No. Also note that the piece of paper could be blank - a null reference. – Sweeper May 31 '21 at 05:51

1 Answers1

0

What you are assigning to 'next' within the constructor is the memory address of another object 'n' (in this case, another Node).

An object variable is simply a reference that points to a real object in the memory heap (one segment in RAM allocated for the JVM).

Conceptually, you can reason about it as a coordinate, a number. Also think that 'n' may be 'null', meaning that next won't refer to any object at by now.

To keep helping to clear your thoughts, what you are creating is an 'instance' that contains a reference to another 'instance' of the same class.

pablozoani
  • 33
  • 5