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 :)
inventory, it is no different from not having the method, because once a user gets a hold of the list, they now have access to an internal component of the object; and can change the list as they see fit.