-1

I'm a moderately experienced Java coder who has always wondered about objects that hold other objects. Suppose I have the following object definitions:

public abstract class food{
    public void eat(){
        // somehow consume this instance
    }
}
public class apple extends food{}
public class orange extends food{}

public class lunchbox{
    public List<food> contents;
    public lunchbox() {
        this.contents = new ArrayList<>();
    }
}

Now suppose I run the below code:

public void foo() {
    lunchbox lunchA = new lunchbox();
    lunchbox lunchB = new lunchbox();
    apple apple = new apple();
    orange orange = new orange();
    lunchA.contents.add(apple);
    lunchB.contents.add(apple);
    lunchB.contents.add(orange);
}

Here, I've created one instance of an apple and one instance of an orange. The apple is stored in both lunchboxes lunchA and lunchB, while the orange is stored in lunchB.

Here's where I get a little confused: Because I'm naming these objects "lunchbox," "apple," and "orange," its easy to imagine real-life lunchboxes, apples, and oranges. In my mind, I can picture two lunchboxes; one with an apple in it, the other with a second apple and an orange in it.

But that's not what's actually happening here, is it? Here, there is one apple instance, and both lunchboxes have a (pointer?) to that instance in their contents lists. If I were to do this:

lunchA.contents.get.(0).eat();

I am actually eating the apple in both lunchboxes, correct?

What is the Java terminology here? What is stored in the lunchboxes' lists? A pointer to a food instance?

And if I wanted separate instances of apples and oranges actually saved within the lunchbox instances, I would need to do this...?

lunchA.contents.add( new apple() );
lunchB.contents.add( new apple() );
lunchB.contents.add( new orange() );

And the above code would mean that lunchbox objects are container objects?

Apologies for the scattershot post, I've always been confused by how this stuff works.

Pete
  • 1,145
  • 2
  • 21
  • 43
  • 2
    For starters this should help with some terminology: [What is the difference between a variable, object, and reference?](https://stackoverflow.com/q/32010172). – Pshemo May 24 '22 at 14:33

0 Answers0