Object to object referencing

Hi,

I have problem referencing to a object from within another object.

Here is my code that is a bit simplified to only show my problem;

class Team {

  String team;
  int elements;
  int maxElements;
  Bubble[] b;

  Team(String tempTeam) {

    this.team = tempTeam;
    this.elements = 0;
    this.maxElements = 100;
    Bubble[] b = new Bubble[maxElements];
  }

  void handleBubbles(Team other, Bubble enemy[], int enemyElements) {
    for (int i=0; i <= this.elements - 1; i++) {
   this.b[i].display();

    }
  }

handleBubbles() is called from my main code.
I get the error at “this.b[i].display();” so I’m obviously referencing wrong. I hope someone here can tell me the correct way to call the display() function that exists inside the Bubble object. The error I get is “NullPointerException”.

Thanks,
Jakob.

1 Like

The problem is in the constructor because you are making a duplicate bubble array which is destroyed when the constructor finishes

I have also modified the loop in handleBubbles. When iterating over an array always use the array length to terminate the loop, less likely to get runtime errors.

class Team {

  String team;
  int elements;
  int maxElements;
  Bubble[] b;

  Team(String tempTeam) {

    this.team = tempTeam;
    this.elements = 0;
    this.maxElements = 100;
    b = new Bubble[maxElements];
  }

  void handleBubbles(Team other, Bubble enemy[], int enemyElements) {
    for (int i=0; i < b.length; i++) {
      b[i].display();
    }
  }

2 Likes

I totally missed that! Thanks a lot for your answer!