Java OCA OCP Practice Question 2210

Question

Which are the minimum changes needed to make this class immutable?

1:   public class Rectangle { 
2:      String c; //from  w  w w . j a  v a  2s  .  c o m
3:      public Rectangle(String c) { 
4:         this.c = c; 
5:      } 
6:      public String getC() { 
7:        return c; 
8:      } 
9:      private final void setC(String newC) { 
10:        c = newC; 
11:    } 
12:  } 
  • I. Make c private and final.
  • II. Make the getter method final.
  • III. Remove the setter method.
  • A. None. It is already immutable.
  • B. I
  • C. I and II
  • D. I and III
  • E. II and III
  • F. I, II, and III


F.

Note

This class is not immutable.

Most obviously, an immutable class can't have a setter method.

It also can't have a package-private instance variable.

The getter method should be final so the class prevents a subclass from overriding the method.

Since all three of these changes are needed to make this class immutable, Option F is the answer.




PreviousNext

Related