简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM