I'm trying to access an array from one class in a different class and am completely stuck on how to do it. Here's the 2 classes....
1 Answer
You have defined field as public, so you could access it with
Item[] items = snacks.stock
But wait, ask a question is this a good way and can we do better. Yes why not define a proper access control over that field. It's very specific to one vending machine, so don't you want to encapsulate it? So define the field as:
private Item[] stock; //Array of Item objects in machine
^^^^^^^
Now this field wont be accessible to outside world. Now how do i access the field? Expose a getter method like:
public Item[] getStocks() {
return stocks;
}
And then use that getter method from vending machine like:
Item[] items = snacks.getStocks();
2 Comments
Ryan Dorman
I switched it to private then created a getter but it still will not print in the other class. When I state: System.out.print(stock); it gives me an error that stock can not be resolved as a variable. Help?
SMA
No you can't directly access stock. You will need
System.out.print(snacks.getStocks());