user10595057
user10595057

Reputation:

How to refer to the instance of a class from within the instance

I have a Class named Store and in that class, I have a list of items called itemList. The item itself is a class. I am trying to create an instance of the Class Store and the Item class has an argument Store which is used to refer to the store in which it is available.

So I want to use the instance of Store inside of which I am creating the itemList containing the Item which require a store argument and the store argument that I want here is the one that is being instantiated.

Store(
    id: 's1',
    name: 'PizzaHut',
    itemList: [
      Meal(
        id: "i1",
        name: "Sample Item",
        description: "Some Description",
        price: 134,
        store: ??????,   ////   Here I want to refer to the parent instance of the Store class   ////
      ),
    ],
  ),

Upvotes: 2

Views: 300

Answers (1)

Richard Heap
Richard Heap

Reputation: 51770

You can't. At the time that you create the Meal so that you can add it to the List<Meal>, the Store instance doesn't exist. It won't get created until you pass the id, name and itemList to the constructor. Of course, you've had to create the list first, to be able to pass it. Catch-22.

There are several ways to solve this, by breaking it down into steps. You could create the Store first with just id and name and then create the list of meals and finally call a setter on the store instance to pass in the list. (Or create an add method on the store that allows you to add a meal to its list. The choices are almost endless.)

Upvotes: 2

Related Questions