今天我在实例化一个类是编译器报以下错误:
No enclosing instance of type Person is accessible. Must qualify the allocation with an enclosing instance of type Person (e.g. x.new A() where x is an instance of Person).
后来才反应 Java中
不能直接创建实例化内部类对象
百度后得到以下结论:
1:非静态内部类,必须有一个外部类的引用才能创建。
2:在外部类的非静态方法中,因为有隐含的外部类引用this,所以可以直接创建非静态内部类。
3:在外部类的静态方法中,因为没有this,所以必须先获得外部类引用,然后创建非静态内部类。
4:静态内部类,不需要外部类引用就可以直接创建。
5:同时静态的内部类,也不能直接访问外部类的非静态方法。
6:由此可以推测,非静态内部类之所以可以直接访问外部类的方法,是因为创建非静态内部类时,有一个隐含的外部类引用被传递进来。
看到第一个 非静态内部类,必须有一个外部类的引用才能创建。
我想到了不能直接new 于是我这样
Man man = new Person().new Man();
这样成功了