jQuery in Action, 2nd edition*
The moose likes Beginning Java and the fly likes how to implement array of objects??? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "how to implement array of objects???" Watch "how to implement array of objects???" New topic
Author

how to implement array of objects???

doug byrnes
Greenhorn

Joined: Apr 12, 2001
Posts: 6
I am trying to work with an array of objects but I can't get it to work! Can anyone tell me how come this code gives a Null Pointer error:
class bar
{
bar() { }
private int x, y;
public void setcoords(int inx, int iny) {this.x = inx; this.y = iny;}
}
class foo
{
private static bar[] mybar = new bar[100];
public static void main(String[] args)
{
mybar[2].setcoords(2,2); // GIVES NULL POINTER ERROR
}
John Dale
Ranch Hand

Joined: Feb 22, 2001
Posts: 399
In Java "Bar aBar;" declares a reference to an object that must be an instance of Bar. (This is different than in C++.) To create a Bar object and have aBar refer to it, you must do something like "aBar = new Bar();".
The same applies to arrays. Each element of an "array of objects" really holds a reference to such an object. But it is a null reference until you create such an object and assign it to the array element. So try somethink like:
public static void main(String[] args)
{
for (int i=0; i < mybar.length; ++i) mybar[i] = new bar();
mybar[2].setcoords(2,2); // no longer GIVES NULL POINTER ERROR
}
Not that this situation is different for primative types, like int or float.
Michael Hildner
Ranch Hand

Joined: Oct 13, 2000
Posts: 297
Although you have declared an array of bars, you have not initialized any of them, so they're all null.
You could initialize them with someting similar to:
doug byrnes
Greenhorn

Joined: Apr 12, 2001
Posts: 6
thx!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: how to implement array of objects???