How to create an Array of Objects in Java -


i'm trying create array of objects defined subclass (i think that's correct terminology). can see question recurring, implementation still problematic.

my code

public class test {      private class myclass {         int bar = -1;     }      private static myclass[] foo;      public static void main(string args[]) {          foo = new myclass[1];         foo[0].bar = 0;      }        } 

gives error

exception in thread "main" java.lang.nullpointerexception.

in attempt rationalise it, broke down simplest terms:

public class test {      private static int[] foo;      public static void main(string args[]) {          foo = new int[1];         foo[0] = 0;      }        } 

which appears work. don't see difference between 2 examples. (i understand first pointless, myclass contain more data.)

i'm pretty sure question asked here , answered. think implemented solution:

myclass[] foo = new myclass[10]; foo[0] = new myclass(); foo[0].bar = 0; 

but second line of above issues error

no enclosing instance of type test accessible.

i understand arraylist way forward, i'm trying grasp underlying concepts.

nb - might useful know while comfortable programming in general, java first dip object oriented programming.

the reason int works, 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 object)  null boolean                 false 

when initialize array, elements take on default value.

so, when initialize int[], elements 0, no problem using or assigning new value it.

but, when initialize myclass[], elements null, problem when try access member of 1 of elements.

if don't know why accessing null object's members won't work, need take 2 steps , read java book.

additional note:

technically, this:

int[] foo = new int[1]; foo[0] = 0; 

is more this:

myclass[] foo = new myclass[10]; foo[0] = new myclass(); 

not:

myclass[] foo = new myclass[10]; foo[0].bar = 0; 

since you're assigning new value element, rather accessing member of element.

no enclosing instance of type test accessible:

the other answers cover pretty well, , here 3 related questions:

no enclosing instance of type accessible.

no enclosing instance of type server accessible

"no enclosing instance of type" error while calling method class in android


Comments