Ryan Dorman
Ryan Dorman

Reputation: 317

How can I access an array in a different class?

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....

Upvotes: 0

Views: 748

Answers (1)

SMA
SMA

Reputation: 37103

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();

Upvotes: 3

Related Questions