Search code examples
javaclassvariablesinstance-variables

Why using a class as a variable member inside that said class


I am new to Java and been studying it. So I am having trouble to understand what are these and how it being processed by Java also why are we declaring these variables like that. I mean can you educate me on this?

Public abstract class ListItem {
    protected Listitem leftLink = null;
    protected Listitem rightLink = null;
    protected Object value;

    some code here
}

Thanks in advance!


Solution

  • Why declare a Class field which has the ClassName as variable type instead of a int, string... ?

    Because the developer needs to. Sometimes, an instance of a class must reference another instance of the same class. A typical example is the LinkedList.

    Consider a linked list as a sequence of nodes. Each node knows the next one to be linked. Here would be a naive implementation of a node:

    class Node<T> {
        private Node<T> next;
        private T value;
    
        Node(T value) {
            this.value = value;
        }
    
        public T getValue() {
            return value;
        }
    
        void setNext(Node<T> next) {
            this.next = next;
        }
    }
    

    As you can see, the class Node contains a variable member of type Node, to reference the next element of the linked list. Finally, a simplistic implementation of the linked list would be:

    class LinkedList<T> {
    
        private Node<T> first;
        private Node<T> last;
        private int length = 0;
    
        public void add(T value) {
            Node<T> node = new Node<T>(value);
    
            if(length != 0) {
                last.setNext(node);
                last = node;
            }
            else {
                first = node;
                last = node;
            }
    
            length++;
        }
    
        public Node<T> getFirst() {
            return first;
        }
    }
    

    When a new node is added to the collection, the previous last node references it and therefore, becomes the new last node.