在调用超类型构造函数之前无法引用此方法 [英] Cannot reference this before supertype constructor has been called
问题描述
我正在尝试用Java实现循环队列类。为此,我必须创建一个节点类以将元素和指向下一个节点的指针组合在一起。由于是圆形的,因此节点必须能够指向自己。但是,当我去编译下面的代码时,编译器(javac)告诉我我的构造函数(即第5行和第8行)做错了,给出了问题的名称错误,并且我无法弄清楚为什么不是没有工作。
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;}
}
推荐答案
您不能在构造函数中引用此(或超级),因此您应像这样更改代码:
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;}
}
这篇关于在调用超类型构造函数之前无法引用此方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!