Creating instance of inner class outside the outer class in java [duplicate]

二次信任 提交于 2019-12-01 04:37:11

In your example you have an inner class that is always tied to an instance of the outer class.

If, what you want, is just a way of nesting classes for readability rather than instance association, then you want a static inner class.

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);
rachana

Outside the outer class, you can create instance of inner class like this

Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();

In your case

A a = new A();
A.B b = a.new B(5);

For more detail read Java Nested Classes Official Tutorial

Interesting puzzle there. Unless you make B a static class, the only way you can instantiate A is by passing null to the constructor. Otherwise you would have to get an instance of B, which can only be instantiated from an instance of A, which requires an instance of B for construction...

The null solution would look like this:

anotherMethod(new A(new A(null).new B(5)));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!