Creating an instance of an inner class outside the outer class in java

I am new to Java.

My file is A.javaas follows:

public class A {
    public class B {
        int k;
        public B(int a) { k=a; }
    }
    B sth;
    public A(B b) { sth = b; }
}

In another java file, I'm trying to create an object A that calls

anotherMethod(new A(new A.B(5)));

but for some reason I get an error: 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).

Can someone explain how I can do what I want? I really want to instantiate Aand then install it sthand then pass the instance to the Amethod, or is there any other way to do this?

+4
source share
3 answers

In your example, you have an inner class that is always bound to an instance of the outer 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);
+8

,

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

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

Java-

+13

. B , , A, - null . B, A, B ...

null :

anotherMethod(new A(new A(null).new B(5)));
+1

Source: https://habr.com/ru/post/1546658/


All Articles