在调用超类型构造函数之前无法引用它

时间:2014-05-20 08:35:58

标签: java compiler-errors

我正在尝试在Java中实现循环队列类。在这样做的过程中,我不得不创建一个节点类来将元素和指针组合到下一个节点。作为循环,节点需要能够指向自己。然而,当我去编译下面的代码时,编译器(javac)告诉我我的构造函数(即第5行和第8行)做错了,给出了同名的错误,我无法弄清楚为什么它不是不工作

对我的使用不正确的任何帮助和解释表示赞赏。

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;}
}

4 个答案:

答案 0 :(得分:3)

编译错误是

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

基本上,你不能使用&#34; this&#34;来自内部&#34; this(...)&#34;

答案 1 :(得分:2)

你不能在构造函数中引用this(或super),所以你应该改变你的代码:

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 :(得分:0)

在所有情况下你都不需要传递它。因为你可以在其他的construtor中引用它

答案 3 :(得分:0)

无法通过&#34;这个&#34;作为调用构造函数的参数。