Java OCA OCP Practice Question 2222

Question

Which are the minimum changes needed to properly implement the singleton pattern?

1:   public class Main { 
2:      private static Main m; 
3:      private int pageNumber; 
4:      static { 
5:        m = new Main(); 
6:      } /*  www  .  ja  va  2s  .c  o m*/
7:      public static Main getInstance() { 
8:         return m; 
9:      } 
10:     public int getPageNumber() { 
11:        return pageNumber; 
12:     } 
13:     public void setPageNumber(int newNumber) { 
14:        pageNumber = newNumber; 
15:     } 
16:  } 
  • I. Add a private constructor.
  • II. Remove the setter method.
  • III. Remove the static block and change line 2 to instantiate Main.
  • A. None. It is already a singleton.
  • B. I
  • C. I and II
  • D. I and III
  • E. II and III
  • F. I, II, and III


B.

Note

This class is not a singleton because it needs a private constructor.

Having a setter method is fine.

The state of a singleton's instance variables is allowed to change.

The static initializer is fine as it runs at the same line as the declaration on line 2.

Therefore, only the constructor addition is needed, and Option B is correct.




PreviousNext

Related