I'm studying java and my teacher told me that this break with the principle of encapsulation:
private ArrayList<Item> inventory;
inventory = new ArrayList<Item>();
public List<Item> getInventory() {
return inventory;
}
and he told me that I should not return inventory directly because it breaks encapsulation, but I should return a copy instead like this (see below) so we don't want to return it directly. Whats the point of returning two lists, when we just want to change the first (by adding items)?
public List<Item> getInventory() {
return new Arraylist<Item>(inventory);
}
However, his explanation made no sense to me, can anyone help? Thank you for your time :)