在java中创建外部类之外的内部类的实例

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; }
}
Run Code Online (Sandbox Code Playgroud)

在另一个java文件中,我正在尝试创建一个A对象调用

anotherMethod(new A(new A.B(5)));
Run Code Online (Sandbox Code Playgroud)

但由于某种原因,我得到错误: 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();
Run Code Online (Sandbox Code Playgroud)

在你的情况下

A a = new A();
A.B b = a.new B(5);
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请阅读Java嵌套类官方教程

  • 在大多数情况下,这是很好的建议.+1.但是,在这种情况下它不起作用,因为`A`没有默认构造函数. (2认同)

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);
Run Code Online (Sandbox Code Playgroud)