ObjectA
needs a reference to arrA
. Typically this is done by passing it as a parameter to that function:
public class ObjectA {
...
public void doThis(ArrayofObjectA arrA) {
arrA.doSomething(); // <-- Here's the issue
}
}
By doing this, you ensure that a reference is 'in scope' for that function. Normally functions can only 'see' parameters passed to them and member fields of their class. So, the other way it can call doSomething()
is if there is a reference in the class itself:
public class ObjectA {
private ArrayofObjectA arrA;
public ObjectA(ArrayofObjectA a) {
this.arrA = a; ///'this' is optional but makes it clear we are talking about a member field.
}
public void doThis(ArrayofObjectA arrA) {
this.arrA.doSomething(); // <-- Here's the issue
}
}
Note that a 'reference' is essentially some handle that allows you to refer to a particular instantiation of an object. You need a reference to call any non-static method. See this answer for more information on the difference between those two things.
Also note that despite naming your class ArrayofObjectA
, it is not actually an array. There is only one instance of it declared (in your MainClass
) and it (currently) possess no references to any ObjectA
instantiations. More properly you might name this ArrayHolder
:
public class ArrayHolder {
private ObjectA[] arrA;//note that the [] indicates it's an array.
public ArrayHolder() {
this.arrA = new Object[10];//Length of ten
for (int idx=0; idx<10; idx++) {
this.arrA[idx] = new ObjectA(this);//pass new ObjectA a REFERENCE to 'this' object (ArrayHolder)
}
}
public void doSomething() {
//This is now callable from all ObjectA objects.
}
}