Alien[] aliens;
aliens=new Alien[10];
aliens[0].setX(10); //<--- gives me a Null Pointer exception
Java hates me. It wont let me make an array of objects
I know there must be something I'm doing wrong but for the life of me I don't see it. Heres a tiny excerpt from my code which is causing the problem.
Seems simple enough. My Alien class has a println function in the constructor to let me know it was invoked but it never executes. If I change aliens from an array to a single variable and then set it equal to "new Alien();" then the Alien constructor is invoked and I don't get the exception.
I know that isn't very much information but what could possibly make an attempt to make an array of objects not work, even when making a single one works just fine?
In Java, not only do you have to create the array via new, you also have to populate the array via new. Iterate through your newly created array object and fill it with new Aliens.
Quote:Original post by MikeTacular
In Java, not only do you have to create the array via new, you also have to populate the array via new. Iterate through your newly created array object and fill it with new Aliens.
That is to say, new Alien[10] creates a new array to hold objects (specifically, pointers to objects) not new objects themselves.
Yeah thats just creating an array of size 10 to hold 10 Alien objects. So what you would need to follow it up on is
Alien[10] aliens;aliens[0] = new Alien();aliens[1] = new Alien();// etc
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement