因此,在同一文件中创建Node
和List
类并尝试通过main
方法向新创建的List对象添加值之后,出现此错误:>
[line: 60]
Error: No enclosing instance of type List is accessible. Must qualify the allocation
with an enclosing instance of type List (e.g. x.new A() where x is an instance of List).
如果我将Node
类放在一个单独的文件中,并在main
类中创建我的Node
方法并执行相同的命令,那么它将正常工作。所以我很好奇为什么会发生此问题。
这是我的代码
public class List{
Node head;
public class Node{
Node next;
int data;
Node(int data, Node next){
this.data = data;
this.next = next;
}
Node(int data){
this.data = data;
}
public Node getNode(Node n){
return n;
}
}
public void add(Node n){
if(head == null){
head = n;
}
else{
Node t = head;
while(t.next!=null){
t=t.next;
}
t.next = n;
}
}
public void add(int data){
Node n1 = new Node(data);
if(head==null){
head = n1;
}
else{
Node t = head;
while(t.next!=null){
t = t.next;
}
t.next = n1;
}
}
public void show(){
Node t = head;
while(t != null){
System.out.println(t.data);
t = t.next;
}
}
public static void main(String[] args){
Node a1 = new Node(65);
List newList = new List();
newList.add(a1);
newList.show();
}
}