12

I'm new to Java.

My file A.java looks like this:

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 the A object calling

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

but for some reason I get 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 can I do what I want to do? I mean, do I really nead to create instance of A, then set it's sth and then give the instance of A to the method, or is there another way to do this?

burtek
  • 2,576
  • 7
  • 29
  • 37
  • 2
    B does not depend on A so it would make sense to make it static (`public static class B`) - your code will then work. See also: http://stackoverflow.com/questions/9560600/java-no-enclosing-instance-of-type-foo-is-accessible – assylias Jul 01 '14 at 09:39
  • Well, I don't know why I didn't think of using `static`, but it's the solution in fact. Thanks – burtek Jul 01 '14 at 09:41

3 Answers3

35

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

Miral
  • 12,637
  • 4
  • 53
  • 93
rachana
  • 3,344
  • 7
  • 30
  • 49
13

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);
sksamuel
  • 16,154
  • 8
  • 60
  • 108
  • Well, I don't know why I didn't think of using `static`, but it's the solution in fact. Thanks. I'll acept your answer in 9 minutes when I'll be able to do so. – burtek Jul 01 '14 at 09:42
1

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)));
shmosel
  • 49,289
  • 6
  • 73
  • 138