Java OCA OCP Practice Question 1448

Question

Which of these classes properly implement(s) the singleton pattern?

class Answer { //from   w  ww . j  av  a 2 s.  c  o m
  private static Answer instance = new Answer(); 
  private List<String> answers = new ArrayList<>(); 

  public static List<String> getAnswers() { 
    return instance.answers; 
  } 
} 
class Main { 
   private static Main instance = new Main(); 
   private List<String> answers = new ArrayList<>(); 
   public static Main getMain() { 
      return instance; 
   } 
   public List<String> getAnswers() { 
      return answers; 
   } 
} 
  • A. Answer
  • B. Main
  • C. Both classes
  • D. Neither class


D.

Note

The singleton pattern requires that only one instance of the class exist.

Neither of these classes meets that requirement since they have the default no-argument constructor available.

There should have been a private constructor in each class.

Option D is correct.




PreviousNext

Related