Objects in objects

In general an object shouldn’t need to be aware of any other object which “owns” it.

But if you feel you need such feature you can create an “owner” field for it:

/**
 * AppleTree (v1.0.0)
 * GoToLoop (2020/Jul/08)
 * https://Discourse.Processing.org/t/objects-in-objects/22486/2
 */

import java.util.List;

Tree tree;

void setup() {
  tree = new Tree().bearFruit().bearFruit();
  println(tree);
  println(tree.apples);
  exit();
}

class Apple {
  Tree owner;

  Apple() {
  }

  Apple(final Tree tree) {
    owner = tree;
  }

  String toString() {
    return "I'm an " + getClass().getSimpleName() + " from " + owner;
  }
}

class Tree {
  final List<Apple> apples = new ArrayList<Apple>();

  Tree bearFruit() {
    apples.add(new Apple(this));
    return this;
  }

  String toString() {
    return "I'm a " + getClass().getSimpleName();
  }
}
3 Likes