Creating an Array of Objects
19 November, 2014 - 2 min read
I have a class A for example -
A[] arr = new A[4];
But this is only creating pointers (references) to A and not 4 objects. Is this correct? I see that when I try to access functions/variables in the objects created I get a null pointer exception. To be able to manipulate/access the objects I had to do this --
A[] arr = new A[4];
for( int i=0; i<4; i++ )
arr[i] = new A();
I find this odd because in C++ you just say new A[4] and it creates the four objects.
This is correct.
A[] a = new A[4];
creates 4 A variables, similar to doing this
A a1;
A a2;
A a3;
A a4;
now you couldn't do a1.someMethod() without allocating a1 as
a1 = new A();
similarly, with the array you need to do
a[0] = new A();
before using it.
The reason int works, but MyClass doesn't:
From here:
Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any object) null
boolean false
When you initialize an array, all elements take on the default value.
So, when you initialize an int[], all elements are 0, so no problem using that or assigning a new value to it.
But, when you initialize an MyClass[], all elements are null, which is a problem when you try to access a member of one of the elements.
If you don't know why accessing a null object's members won't work, you probably need to take 2 steps back and read a Java book.
Additional Note:
Technically, this:
int[] foo = new int[1];
foo[0] = 0;
is actually more like this:
MyClass[] foo = new MyClass[10];
foo[0] = new MyClass();
not:
MyClass[] foo = new MyClass[10];
foo[0].bar = 0;
since you're assigning a new value to an element, rather than accessing a member of an element.
No enclosing instance of type Test is accessible:
The other answers cover that pretty well, and here are 3 related questions:
No enclosing instance of type is accessible.
No enclosing instance of type Server is accessible
"No enclosing instance of type" error while calling method from another class in Android