Java OCA OCP Practice Question 2505

Question

What changes would need to be made to make the following immutable object pattern correct? (Choose all that apply.)

import java.util.List; 
public class Shape { 

   private String name; 
   private List<Shape> ducklings; 

   public Shape(String name, List<Shape> ducklings) { 
      this.name = name; 
      this.ducklings = new ArrayList<Shape>(ducklings); 
   } //  w w  w .  ja v a2  s .c o  m

   public String getName() { return name; } 

   public List<Shape> get() { return ducklings; } 

   public String hasShapelings(Predicate<Shape> p) { 
      return p.test(this) ? "Quack Quack": ""; 
   } 
} 
  • A. None, the immutable object pattern is properly implemented.
  • B. Mark name and ducklings final.
  • C. Mark the Shape class final.
  • D. Have Shape implement the Immutable interface.
  • E. Remove the hasShapelings() method since any lambda expressions passed to it could modify the Shape object.
  • F. Replace the get() with a method (or methods) that do not give the caller direct access to the List<Shape> ducklings.
  • G. Change the type of List<Shape> to be List<Object>.


B, C, F.

Note

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

B is correct, because all instance variables should be marked final and private for the class to be considered immutable.

C is correct, because it prevents the methods from being overridden.

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

E is also incorrect, because any passed lambda expression would have access to only the public methods of the class.

F is correct, because the mutable object ducklings should not be exposed directly, since this allows the user to modify it.

G is incorrect, because this has nothing to do with immutability.




PreviousNext

Related