0

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 1

3

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();
Sign up to request clarification or add additional context in comments.

2 Comments

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?
No you can't directly access stock. You will need System.out.print(snacks.getStocks());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.