1

Hi it's been a while since I've written java and I can't seem to find what is wrong with this code. I'm implenting deleting a node from a linked list but my program won't compile. I keep getting:

error: non-static variable this cannot be referenced from a static context

Node head = new Node();

It has an error for all my new Node() instances in my main method.

public class NodeDelete{

 class Node {
 int data;
 Node next;

    public Node(){ }
}


Node Delete(Node head, int position) {
    // Complete this method
        int index = 0;
        Node current = head;
        if (position == 0 ){
            head = head.next;               
        }
        else{
            while (index < (position - 1)){ 
                current = current.next;
            }
            current.next = current.next.next;
        }
        return head;
}

    public static void main(String[] args) {
        Node head = new Node();
        head.data = 0;

        Node node1 = new Node();
        node1.data = 1;

        Node node2 = new Node(); 
        node2.data = 2;

        head.next = node1;
        node1.next = node2;           
    }
}
0

3 Answers 3

2

Either make the Node class static. OR take out Node class from the NodeDelete class. That will solve the issue.

The Node class is a non-static inner class of NodeDelete, so it is like a member of the NodeDelete class. To access any member in the static context, instance of the class is required. That is why you are getting the compile time error here.

Note : The constructor you have defined in the Node is same as the default constructor. So no need to define it. It is redundant.

Making Node class static:

static class Node {
  int data;
  Node next;

  public Node(){  }  // This is same as the default constructor. So this can be remove.
}

OR

Take out the same implementation from the NodeDelete class.

Sign up to request clarification or add additional context in comments.

Comments

0

Node is a non-static inner class. Therefore a instance of the containing class is needed to construct the instance:

NodeDelete nd = ...
Node node = nd.new Node();

Alternatives:

  • Make Node a static inner class
  • Make Node a top level class

Since there is no reference to a NodeDelete in Node's methods I recommend making Node static.

Comments

0

Another option not given yet, though not my favorite, would be to instantiate an instance of the class which contains the main method then use it to instantiate the inner class. Like so...

NodeDelete nd = new NodeDelete(...);
Node n = nd.new Node(...);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.