bur*_*tek 7 java class inner-classes
我是Java的新手.
我的文件A.java看起来像这样:
public class A {
    public class B {
        int k;
        public B(int a) { k=a; }
    }
    B sth;
    public A(B b) { sth = b; }
}
在另一个java文件中,我正在尝试创建一个A对象调用
anotherMethod(new A(new A.B(5)));
但由于某种原因,我得到错误: No enclosing instance of type A is accessible. Must qualify the allocation with an enclosing instance of type A (e.g. x.new B() where x is an instance of A).
有人可以解释我怎么能做我想做的事情?我的意思是,我真的需要创建实例A,然后设置它sth然后给出方法的实例A,还是有另一种方法来做到这一点?
rac*_*ana 23
在外部类之外,您可以像这样创建内部类的实例
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
在你的情况下
A a = new A();
A.B b = a.new B(5);
有关更多详细信息,请阅读Java嵌套类官方教程
mon*_*ack 11
在您的示例中,您有一个内部类,它始终绑定到外部类的实例.
如果,你想要的只是一种嵌套类的可读性而不是实例关联的方式,那么你需要一个静态的内部类.
public class A {
    public static class B {
        int k;
        public B(int a) { k=a; }
    }
    B sth;
    public A(B b) { sth = b; }
}
new A.B(4);