How can class name be used as data type?

Viewed 2120
public class node {

    int data;
    node next;

    node(int data){
        this.data = data;
    }
}

This is a class that I saw online for a linked list. I am not sure how it used node next.

For example, int data is creating variable data with type int. But then node next is creating a variable named next with type node? But I thought there is no such type as a node.

Could someone please explain this to me?

Thank you for your time.

2 Answers

This will be a little bit clearer if we use correct style:

public class Node {
    int data;
    Node next;

    Node (int data) {
        this.data = data;
    }
}

Node is a class. Each Node instance has a field (data) to hold an integer value, and a field (next) to hold a reference to another Node instance.

(As noted in the comments, all Java classes are types, so Node next; is declaring a field whose name is next and whose type is Node. Furthermore, every Node instance will have one of these fields ... that can refer to another Node instance.)

So, to create a linked list from Node instances, you link one Node to the next one in the list using (naturally) the next field. The last Node in the list (typically) has a null in its next field.


But I thought there is no such type as a node.

Every Java class is a type, and we just defined node (or more correctly Node) as a Java class.

So, it is just creating a new object called next. Am I right?

Not exactly. You would be creating an object (a Node instance) and assigning the object's reference to the next field of some other Node instance.

The object is not called next. It is the field that is called next. And the field contains a reference to an object rather than an object itself.

(These small distinctions in the terminology are actually important to understanding what is really going on.)

Sounds like you're mixing up Primitive types with Reference types. It's important going forward to always differentiate between the two. It seems like you're just starting out so you probably were first introduced to Primitive types like int, double, char and so on. Well reference types are ones that we define with the class keyword. When you are making a class you can think of it as also making a new type. So you can think of the node class in your example as creating a type node.

Related