Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an Array of Objects in Java

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.

like image 796
KDM Avatar asked May 06 '13 10:05

KDM


1 Answers

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;
like image 82
Rahul Bobhate Avatar answered Sep 21 '22 08:09

Rahul Bobhate