1

I've came across with the next code lines, which are part of the implementation of a Node class :

public class Node {

    private String data;
    private Node next;

I wonder how is it possible to use private Node next; as a field of Node ? How come this 'self-instance' is legal and how does it work ? I'll be grateful if anyone could explain this.

3 Answers3

2

Node next will just keep a reference to a different instance of Node class, which means Node class has-a Node.

I'm guessing that class belongs to a simple 'linked list' implementation, where each node keeps a reference to the next node in the list.

ssantos
  • 16,001
  • 7
  • 50
  • 70
1

You probably meant something on these terms

  public class Node {

        private int info;
        private Node next;

        Node(int info, Node next) {
            this.info = info;
            this.next = next;
        }

When you actually use this in a linked list kind of structures the next points to another (or same) kind of object of type Node

Prateek
  • 1,916
  • 1
  • 12
  • 22
1

Is not a self-instance, but, it will refer a instance of an object on memory, of the same type, a Node.

Att: The reffered object can be itself.

Cold
  • 787
  • 8
  • 23
  • That's what i've asked - how come the reffered object could be itself ? –  Oct 09 '13 at 07:19
  • Well, you can look at `next` variable as a recipient that recieves an address of memory of `Node` type. When u create a `Node`, it can store on `next` variable (an recipient) the memory address of an variable of `Node` type. It´s clear? – Cold Oct 09 '13 at 11:02
  • Or, u can see a `Node` as a house. Every house has an address, and inside of every house u can have a paper with address of other houses. In my house, i can put on this paper the reference of my own house. – Cold Oct 09 '13 at 11:03