# Object to object referencing

**URL:** https://discourse.processing.org/t/object-to-object-referencing/4598
**Category:** Coding Questions
**Created:** [October 18, 2018, 1:39pm UTC](https://discourse.processing.org/t/object-to-object-referencing/4598 "2018-10-18T13:39:21Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![jakstb](https://avatars.discourse-cdn.com/v4/letter/j/e19b73/32.png) [@jakstb](https://discourse.processing.org/u/jakstb)
#### Post date: [October 18, 2018, 1:39pm UTC](https://discourse.processing.org/t/object-to-object-referencing/4598/1 "2018-10-18T13:39:21Z")

</div>

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;

```auto
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.

---

<div class="post-metadata">

### Author: ![quark](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/quark/32/26_2.png) [@quark](https://discourse.processing.org/u/quark)
#### Post date: [October 18, 2018, 3:14pm UTC](https://discourse.processing.org/t/object-to-object-referencing/4598/2 "2018-10-18T15:14:53Z")

</div>

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.

```auto
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();
    }
  }

```

---

<div class="post-metadata">

### Author: ![jakstb](https://avatars.discourse-cdn.com/v4/letter/j/e19b73/32.png) [@jakstb](https://discourse.processing.org/u/jakstb)
#### Post date: [October 18, 2018, 7:33pm UTC](https://discourse.processing.org/t/object-to-object-referencing/4598/3 "2018-10-18T19:33:51Z")

</div>

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