这种情况一般发生在“在静态方法里面使用内部类”
测试代码:
public class Test {
public static void main(String[] args) {
A a = new A(1);
}
class A {
int x;
public A() {}
public A(int x) {
this.x = x;
}
}
}
上面这份代码在main函数里面会发生编译错误,为了解决问题,让我们先看看编译器的提示:
编译器告诉我们,没有可访问的Test类的实例,意味着下面将要使用实例,那个地方使用了呢?看后面的括号里面,"x.new A()",new A()实际上是x.new A(),其中x是Test的一个实例。所以我们可以先创建Test的一个实例,然后用这个实例的new方法new一个A()出来。
于是可以改成下面的代码:
public class Test {
public static void main(String[] args) {
Test test = new Test();
A a = test.new A(1);
}
class A {
int x;
public A() {}
public A(int x) {
this.x = x;
}
}
}
明白了这一点就可以解释下面的代码了:
public class Test {
public static void main(String[] args) {
Test test = new Test();
A a = test.new A(1);
B b = new B(2);//这里的B不是一个内部类,所以不存在上述问题所以可以直接写new
A.AA aa = a.new AA(3);
}
class A {
int x;
public A() {}
public A(int x) {
this.x = x;
}
class AA {
int x;
AA() {}
AA(int x) {
this.x = x;
}
}
}
}
class B {
int x;
public B() {}
public B(int x) {
this.x = x;
}
}
或者用令外一种方法,将内部类改成静态的:
public class Test {
public static void main(String[] args) {
A a = new A();
}
static class A {
int x;
public A() {}
public A(int x) {
this.x = x;
}
}
}