Encapsulation for mutable objects in Java

好久不见. 提交于 2019-12-01 21:59:00

问题


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;

回答1:


You would have replace:

return list;

with:

return new ArrayList<Integer>(list);

Otherwise the client can do...

foo.getList().add(5);

breaking encapsulation.




回答2:


we do this?

ArrayList<Integer> list2=list;
return list2;

No, it says a copy of the object, not a copy of the reference.

ArrayList<Integer> list2= new ArrayList<>();
list2.addAll( list );
return list2;

Or as pointed out, ArrayList has a copy constructor that will add all elements from another list to the new list. The above three lines are intended primarily to be clear what is being done.




回答3:


You can use the copy constructor

return new ArrayList<Integer>(list);



回答4:


return list;

would return the reference to your private ArrayList list this is where the encapsulation breaks.

ArrayList<Integer> list2=list;
return list2;

Even here also you are simply passing the reference of your list to list2 You can try -

ArrayList<Integer> list2 = new ArrayList<Integer>();
list2.addAll(list);


来源:https://stackoverflow.com/questions/34503190/encapsulation-for-mutable-objects-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!