1

I implement a linked list from scratch in java according to the book of EPI. However this is an error when creating list nodes.

My code is

public class Example {

    class ListNode<T> {
        public T data;
        public ListNode<T> next;

        ListNode(T data, ListNode<T> next) {
            this.data = data;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        System.out.println("Hello world.");
        ListNode<Integer> p1  = new ListNode<Integer>(123, null);
    }

}

This error is

Example.java:19: error: non-static variable this cannot be referenced from a static context
        p1 = new ListNode<Integer>(123, null);
             ^
1 error

It works when I revise it a little bit.

public static class ListNode<T> {
    public T data;
    public ListNode<T> next;

    ListNode(T data, ListNode<T> next) {
        this.data = data;
        this.next = next;
    }
}

But why I should add static?

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226

3 Answers3

0

It works when I revise it a little bit.

public static class ListNode<T> {
        public T data;
        public ListNode<T> next;

        ListNode(T data, ListNode<T> next) {
            this.data = data;
            this.next = next;
        }
    }

But why I should add static?

0

You can't access non-static variables from static, but you can access static from non-static. Your main method is static, that's why you have an error. Read more about the difference between static and non-static.

I want to know the difference between static method and non-static method

I want to know the difference between static class and non-static class

Community
  • 1
  • 1
Mihail Petkov
  • 1,535
  • 11
  • 11
0

In the example you've provided you are attempting to directly instantiate an inner class.

An inner class is tied to an instance of their outer class (See: JLS 8.1.3). So in short, you cannot have a Example.ListNode instance if there is no Example instance!

So this leaves you the following options:

  1. Move ListNode out of Example so that it's a top level class. You will then be able to instantiate ListNode in your main method.
  2. Mark ListNode as static which effectively makes it otherwise behave as a top level class.
  3. Create an Example instance in main. For example Example example = new Example();. Then you should be able to create instances of ListNode by calling new example.ListNode();.
vpiTriumph
  • 3,116
  • 2
  • 27
  • 39