首先看一段代码
public class Test03 {
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public static void main(String[] args) {
ListNode head=new ListNode(1);
}
}
上述Test03的main函数是static,new了一个ListNode对象,就会编译错误,No enclosing instance of type Test03 is accessible. Must qualify the allocation with an enclosing instance of type Test03 (e.g. x.new A() where x is an instance of Test03).
可以这样理解,内部类相当于类的一个成员,在类的静态函数中是无法访问非静态成员的,所以会有上述编译错误,建议以后这种编程题,把ListNode类写在Test03外边(推荐),而不是内部类的形式。或者把ListNode声明为static的。