[英]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:
公开如下的getter方法:
public Item[] getStocks() {
return stocks;
}
And then use that getter method from vending machine like: 然后在自动售货机中使用该getter方法,例如:
Item[] items = snacks.getStocks();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.