Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 948
burtek Avatar asked Jul 01 '14 09:07

burtek


1 Answers

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

like image 103
rachana Avatar answered Nov 03 '22 00:11

rachana