Cannot reference this before supertype constructor

2020-03-31 07:04发布

问题:

I'm attempting to implement a circular queue class in Java. And in doing so I had to created a node class to group together elements and pointers to the next node. Being circular, the nodes need to be able to point to themselves. However when I go to compile the code below, the compiler (javac) is telling me I'm doing something wrong with my constructors (namely lines 5 and 8) giving the error of the question's namesake, and I cannot figure out why it isn't working.

Any help and explanation of why my usage is incorrect is appreciated.

public class Node<Key>{
    private Key key;
    private Node<Key> next;
    public Node(){
        this(null, this);
    }
    public Node(Key k){
        this(k, this);
    }
    public Node(Key k, Node<Key> node){
        key = k;
        next = node;
    }
    public boolean isEmpty(){return key == null;}
    public Key getKey(){return key;}
    public void setKey(Key k){key = k;}
    public Node<Key> getNext(){return next;}
    public void setNext(Node<Key> n){next = n;}
}

回答1:

You cannot refer tho this (or super) in a constructor, so you should change your code like this:

public class Node<Key>{
    private Key key;
    private Node<Key> next;
    public Node(){
    key = null;
        next = this;
    }
    public Node(final Key k){
    key = null;
        next = this;
    }
    public Node(final Key k, final Node<Key> node){
        key = k;
        next = node;
    }
    public boolean isEmpty(){return key == null;}
    public Key getKey(){return key;}
    public void setKey(final Key k){key = k;}
    public Node<Key> getNext(){return next;}
    public void setNext(final Node<Key> n){next = n;}
}


回答2:

The compile error is

Cannot refer to 'this' nor 'super' while explicitly invoking a constructor

Basically, you cannot use "this" from inside "this(...)"



回答3:

You dont need to pass it in all cases. since you can refer to it in the other construtor



回答4:

Can not pass "this" as a parameter to call the constructor.