Search code examples
javaclassinterfacestaticparameterized

Inner interface in generates errors only when outer class is parameterized? Why?


The abstract method getNextNode generates the error, "cannot make a static reference to the non-static type Node," but only if LinkedList is parameterized. If I remove the generic from LinkedList the error goes away. Why?

public class LinkedList<T> {
    Node head;
    public LinkedList() {
        head = new Node();
    }
    private class Node {

    }

    interface stuff {
        public Node getNextNode();//ERROR Cannot make a static reference to the non-static type Node
    }
}

Solution

  • As the error is trying to tell you, you can't use a generic type without its parameter.

    Node is actually LinkedList<T>.Node. Since your interface isn't generic (interfaces don't inherit type parameters from the containing class), there is no T it can substitute.

    You can fix this by making the Node class static, so that it doesn't inherit the type parameter from its containing class.
    However, you don't actually want to do that, since the Node should be generic.

    You actually need to make your interface generic as well, so that it can specify a T.