0

I understand that in c self-referential structures are allowed but the self-included ones are not. Borrowing the example here:

Invalid:

struct a
{
    int someVar;
    a bad;
};

Valid:

struct a
{
    int someVar;
    a* good;
};

But in Java the following class is valid:

class Node {
    int val;
    Node next;
}

This looks more like the invalid example in c. My question is: why is this legal in Java?

I have a feeling that this is related to the fact that in Java you only have access to references (like pointers), not the actual objects, but I still don't fully understand this. And searching for "self-referential in Java" does not give a lot of related information. Can anyone give some hints? Thanks!

Patrick
  • 555
  • 1
  • 6
  • 25

1 Answers1

1

Java hides some implementation details from you that C does not.

In Java, any instance of a class is a reference i.e. a pointer to an object without explicitly using a pointer.

In C there are no references, only values. So you need to explicitly use a pointer value to hold the address of an object to essentially have a reference to it.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • Oh right! Just to make sure, then is it correct to say that `Node` in `Node next` is different from that in `class Node`? The former means a reference to `Node`, the latter is the actual object? – Patrick Aug 08 '21 at 02:35
  • @Patrick The point where `class Node` appears is the start of the definition of the class. `Node next` is defining a variable of that type, and in Java all object variables are references. – dbush Aug 08 '21 at 02:37