I have a problem passing array of objects into functions. My problem is the following:
Class A, B, and C belong to the same package, and only the important code is shown below:
public class A { public A() {} }
public class B {
private A myObj1[]; public A() { myObj1 = new A[25]; }
public A[] function1() {...}
public static void main(String[] args) { B myObj2 = new B(); A myObj3[]; myObj3 = myObj2.function1(); } }
public class C {
private B myObj4; public C() { myObj4 = new B(); }
public void function2() { A temp[]; temp = myObj4.function1(); } }
Notice how main method of class B is very similar to function2 method of class C. MY problem is that when I run the main method of class B, it runs perfectly and the method runs
as I wanted it to run. When I run or call the function2 method from class C, Java gives me Null
Pointer Exception. I am using the same syntax in the same function! Why is one working and not
the other?! I even tried to initialize the temp variable before calling the function:
A temp[]; temp = new A[25]; temp = myObj4.function1();
I found it! My constructor for class C, didn't have the proper initialization:
instead of this:
private B myObj4; public C() { myObj4 = new B(); }
I had:
private B myObj4; public C() { B myObj4 = new B(); }
so I didn't initialize the private member myObj4, instead, I made a new one in the constructor which would never be accessed later, there my private member myOBj4 remained unitialized!