1

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!

4

2 回答 2

4

您不需要使用A来访问B类构造函数。您已经在A类实例上访问它。只需将您的声明更改为:

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

参考:

当然,该赋值必须在某些方法、构造函数或初始化程序中。您不能像这样在类中直接使用语句。课堂作业也有同样的问题A

所以,你应该把类改成C这样:

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

    {
        a.b[0] = a.new B(); 
    }
}
于 2013-09-05T05:38:38.443 回答
2

第二行b[0] = new B(); 应该在任何方法内。这样做

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();
    }
}
于 2013-09-05T05:43:43.417 回答