Java OCA OCP Practice Question 2635

Question

What changes need to be made to make the following immutable object pattern correct?

(Choose all that apply.)

import java.util.List; 
public class Square { 
   String name; // www.  ja v a 2  s . c om
   private final List<Square> l; 
   public Square(String name, List<Square> l) { 
      this.name = name; 
      this.l = l; 
   } 
   public String getName() { return name; } 
   public List<Square> getSquareList() { return l; } 
} 
  • A. None; the immutable object pattern is properly implemented.
  • B. Have Square implement the Immutable interface.
  • C. Mark name final and private.
  • D. Add setters for name and List<Square> l.
  • E. Replace the getSquareList() method with methods that do not give the caller direct access to the List<Square> l.
  • F. Change the type of List<Square> to List<Object>.
  • G. Make a copy of the List<Square> l in the constructor.
  • H. Mark the Square class final.


C, E, G, H.

Note

A is incorrect, as there are definitely some problems with the immutable objects implementation.

B is incorrect, as there is no such thing as the Immutable interface defined in the Java API.

C is correct, as all instance variables should be private and final to prevent them from being changed by a caller.

D is incorrect, as adding settings is the opposite of what you do with the immutable object pattern.

E is correct, since List<Square> is mutable, all direct access should be removed.

F is incorrect, as this has nothing to do with immutability.

G is correct, as we need to copy the mutable List<Square> to prevent the caller of the constructor from maintaining access to a mutable structure within our class.

H is also correct, as it prevents the methods of the class from being overridden.




PreviousNext

Related