Question

I have not been able to figure this out for quite sometime now after searching a lot of forums online.

I have a class A and a nested class B in a File A.java Also another class C in File C.java

Now I declare an array of object B in class A but I can neither access nor initialize the array elements in Class A or Class C.

public class A{
    public B b[] = new B[15]; //compiles
    b[0] = new B(); //does not compile
    // b[0] = this.new B(); //does not compile either

    public class B{
    }

}

Now in Class C, if I do the following:

public class C{
A a = new A(); //compiles
a.b[0] = a.new A.B(); //does not compile
}

Can anyone please help? I think I am doing some basic error in syntax while trying to access nested instance arrays. Thanks!

Was it helpful?

Solution 2

Second line b[0] = new B(); should be inside any method .Do like this

package com.sample;

public class A {
    public B[] b = new B[15];

    /*
     * public A() {
        b[0] = new B();
    *}

    */

    public class B {
    }
}

C.java

 package com.sample;

public class C {
    A a = new A();
    public C()
    {
        A a=new A();
        a.b[0]=a.new B();
    }
}

OTHER TIPS

You don't need to use A to access B class constructor. You are already accessing it on A class instance. Just change your statement to:

a.b[0] = a.new B();

Reference:

And of course, that assignment has to be inside some method, constructor, or initializers. You can't have statements directly inside a class just like that. Same issue with the assignment in class A.

So, you should change class C to something like this:

class C {
    A a = new A(); //compiles

    {
        a.b[0] = a.new B(); 
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top