I'm trying to create an array of objects as defined by a subclass (I think that's the correct terminology). I can see that the question is recurring, but implementation is 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 the error
Exception in thread "main" java.lang.NullPointerException.
In an attempt to rationalise it, I broke it down to simplest terms:
public class Test {
private static int[] foo;
public static void main(String args[]) {
foo = new int[1];
foo[0] = 0;
}
}
Which appears to work. I just don't see the difference between my two examples. (I understand that my first is pointless, but MyClass will ultimately contain more data.)
I'm pretty sure the question is asked here and is very well answered. I think I implemented the solution:
MyClass[] foo = new MyClass[10];
foo[0] = new MyClass();
foo[0].bar = 0;
but the second line of the above issues the error
No enclosing instance of type Test is accessible.
I do understand that ArrayList would be a way forward, but I'm trying to grasp the underlying concepts.
NB - It might be useful to know that while very comfortable with programming in general, Java is my first dip into Object Oriented programming.
The class
MyClass
is an inner class
, and not a subclass. Non-static inner classes can be accessed by creating an object of class enclosing the inner class. So, if you want to access the inner class, you would have to create an object of outer class first. You can do it by:
Test t = new Test();
MyClass[] foo = new MyClass[10];
foo[0] = t.new MyClass();
foo.bar = 0;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With