Win a copy of Rust Web Development this week in the Other Languages forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

how to implement array of objects???

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
}
 
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 297
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thx!
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic