Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an variable with the class name as the data type in java

I'm going through a code for linked list operations on the internet and I found the following code snippet which i cannot understand.

class Node 
{
    int data;
    Node node; //reference to the next node
    :
    :
}

I've learned that Node node; line is the reference to the next node as nodes of linked list contain data and address of the next node.

But I cannot understand the concept behind it.

Can anybody explain what is the java concept/ theory if a variable is defined with the class name as it's Data Type?

like image 478
Indi Avatar asked May 24 '26 11:05

Indi


1 Answers

Can anybody explain what is the java concept/ theory if a variable is defined with the class name as it's Data Type?

There is no such concept or theory.

From the Java language perspective, a variable name can be anything as long as it conforms to the required syntax.

From a Java style perspective, a variable name should convey meaning to the reader. But it is up to the author of the code to decide how to convey the meaning and what / how much meaning needs to be (explicitly) conveyed.

In this case, the author has decided that they will simply use node as the variable name. That conveys no meaning in addition to the obvious: it is a "node". The actual intended meaning for this variable is conveyed by the comment:

//reference to the next node

but you could probably figure that out by reading the rest of the code in the Node class and/or the code that uses the class.

For what it us worth, I would probably called the variable next rather than node. But I probably would not have called out the author's choice as incorrect in a code review.


As a general statement, there are differing opinions on what and how much meaning variable names should convey. But there are no generally accepted rules. So you need to be prepared read the code rather than relying on the variable names.

This can be a problem if the code is complicated, or if you are trying to a learn about a new (to you) kind of data structure. But in the latter case, the solution may be to find a better code to learn from.

For instance, any good textbook on Data Structures will have example code for linked lists. The code should be better written and should have accompanying text to explain it. And if you don't want to buy / borrow a textbook, you can probably find better example code on the internet to learn from.

like image 61
Stephen C Avatar answered May 26 '26 07:05

Stephen C