我读到没有外部类的实例就无法创建内部类的实例。但是,当我尝试使用内部类的实例作为外部类的实例成员来创建其实例时,它就起作用了。
我知道它是通过对我的外部类对象的引用创建一个内部对象,但这是正确的方法吗?
下面是我的代码段:
public class TestInner {
private Nonstatic non = null;
private static int access = 4;
public class Nonstatic {
void hello() {
access = 90;
}
}
public static void main(String[] args) {
TestInner outer = new TestInner();
TestInner.Nonstatic innern= outer.new Nonstatic();
System.out.println("Non static obj1 is "+innern);
outer.testinnerObj();
}
public void testinnerObj() {
non = new Nonstatic();
System.out.println("Non static obj2 is "+non);
non.hello();
}
}
您正在编写“如果没有外部类实例,则无法创建内部类实例”。这就是您正在做的。
首先,您创建“外部”类的实例:
TestInner outer = new TestInner();
然后,您创建“内部”类的实例-它仅存在在外部范围内:TestInner.Nonstatic innern= outer.new Nonstatic();
因此,问题可能归结为:是的,您正在静态main方法中创建对象。但这无关紧要,因为您使用的语法outer.new
在外部范围内创建它。
希望有所帮助。