I have two classes:
public class A{
int money;
ArrayList<Item> boughtItems;
.
.
public void addBoughtItem(Item item){
.
.
}
public void adjustMoney(int adjustAmount){
money = money + adjustamount;
}
}
and another class :
public class B{
ArrayList<Item> itemsForSale;
.
.
public Item sellMeItem(Item item){
.
.
return itemsForSale.get(...);
}
}
Now in the main, I start an instance of class A, and an instance of class B.
inside class B, whenever I sell them an item, I want to update the purchasedItems and adjust the money of the class A instance in realtime (that means, inside the sellMeItem function of class B.)
Therefore I think I need the A instance to be global.
How can I reach the A object that is in the main from inside the class B sellMeItem function? (and class B instance is also in the main)
Not really, you could simply pass a reference to your instance of A to B, for example via a constructor:
Then you can access
ain B. And in your main:However, the fact that the 2 classes are so intimately related probably means that the way you have split responsibilities among them is not optimal.