Java OCA OCP Practice Question 216

Question

Given:

1. import java.util.*;
2. class Main {/*w w w.j  a  v a  2 s  .c  o  m*/
3.   private String name;
4.   private ArrayList<Integer> list;
5.   Main() { list = new ArrayList<Integer>(); }
6.
7.   String getName() { return name; }
8.   void addToList(int x) { list.add(x); }
9.   ArrayList getList() { return list; }
10. }

Which lines of code if any break encapsulation?

Choose all that apply.

  • A. Line 3
  • B. Line 4
  • C. Line 5
  • D. Line 7
  • E. Line 8
  • F. Line 9
  • G. The class is already well encapsulated


F is correct.

Note

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.




PreviousNext

Related