Java OCA OCP Practice Question 1484

Question

Which of these classes is/are immutable?

public class Shape { 
   private final String name; 
   private final List<Integer> counts; 
   public Shape(String name, List<Integer> counts) { 
      this.name = name; 
      this.counts = new ArrayList<>(counts); 
   } /*from   w  w w . j a v  a  2  s .  c  o m*/
   public final String getName() { 
      return name; 
   } 
   public final List<Integer> getCounts() { 
      return new ArrayList<>(counts); 
   } 
} 

public class Rectangle { 
   private final String name; 
   private final List<Integer> counts; 
   public Rectangle(String name, List<Integer> counts) { 
      this.name = name; 
      this.counts = new ArrayList<>(counts); 
   } 
   public String getName() { 
      return name; 
   } 
   public List<Integer> getCounts() { 
      return new ArrayList<>(counts); 
   } 
} 
  • A. Shape
  • B. Rectangle
  • C. Both classes
  • D. Neither class


A.

Note

An immutable class must not allow the state to change.

The Shape class does this correctly.

While the class isn't final, the getters are, so subclasses can't change the value returned.

The Rectangle class lacks this protection, which makes it mutable.

Option A is correct.




PreviousNext

Related