Home > OS >  Can a class be declared as a variable?
Can a class be declared as a variable?

Time:01-05

I am new in programming.

While I was surfing on the internet I found a code that has this class.

class Node {
private Node link = null;
private int data = 0;

My question is that, what is this "Node" (on the second line) under the class Node{

Is this a variable? What is it called? And what is its purpose?

CodePudding user response:

In Java a variable is can contain a reference to an object. The pattern you show is common in list nodes: a node contains a value and a reference to the next node.

Let us look at your code:

class Node {                  // Ok, we are defining a class named Node
    private Node link = null; // Ok we have a member reference to another Node object
                              // and by default it is initialized to null
    private int data;         // an integer member variable
    ...
}

CodePudding user response:

Sometimes in one class, we need an attribute with the type of the same class. For example, consider this class:

class Person{
    private Person father;
    private String name;

    //and more
}

In this case, we use an Object of type 'Person' in the 'Person' class, because each person has a father, and the father is a Person too.

So we can use a class as a variable in another class.

  •  Tags:  
  • Related