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

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

任何有关我的使用不正确的帮助和解释,这是值得赞赏的。

public class Node{ private Key key; private Node next; public Node(){ this(null, this); } public Node(Key k){ this(k, this); } public Node(Key k, Node 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 getNext(){return next;} public void setNext(Node n){next = n;} } 

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

 public class Node{ private Key key; private Node next; public Node(){ key = null; next = this; } public Node(final Key k){ key = null; next = this; } public Node(final Key k, final Node 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 getNext(){return next;} public void setNext(final Node n){next = n;} } 

编译错误是

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

基本上,你不能在“ this(...) ”里面使用“ this

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

无法传递“this”作为参数来调用构造函数。