I was studying the "Java SE 7 Programmer I & II Study Guide" and I did not understand the explanation below.
class Fortress{
private String name;
private ArrayList<Integer> list;
Fortress() {list=new ArrayList<Integer>;
String getName{return name;}
void addToList(int x){list.add(x);}
ArrayList getList(){return list;} // line 1
}
Which lines of code break encapsulation? Answer: line 9. "When encapsulating a mutable object like an ArrayList, your getter must return a reference to a copy of the object, not just the reference to the original object".
I did not either understand the explanation or how to modifiy the original code.
So in the getList() instead of
return list;
Should we do this?
ArrayList<Integer> list2=list;
return list2;
You would have replace:
return list;
with:
return new ArrayList<Integer>(list);
Otherwise the client can do...
foo.getList().add(5);
breaking encapsulation.