Java OCA OCP Practice Question 2378

Question

Given the following definition of class Main, which option, when replacing //INSERT CODE HERE//,

implements the Singleton pattern correctly? (Choose all that apply.)


class Main {
    private static String name;
    private static Main king = new Main();
    // INSERT CODE HERE //
    public static Main getInstance() {
            return king;
    }
}
a  private Main() {}

b  private Main() {
       name = null;//w ww  . j a v a  2s  .c o  m
   }

c  private Main() {
       name = new String("Main");
   }

d  private Main() {
       if (name != null)
           name = new String("Main");
   }

e  None of the above


a, b, c, d

Note

All the options are trying to confuse you with the correct implementation of method getInstance() of a class that uses the Singleton pattern with its constructor.

A class that implements the Singleton pattern should have a private constructor, so no other class can create its objects.

The implementation of the constructor isn't detailed by the Singleton pattern.

The class may choose to include or exclude whatever it feels is good for it.




PreviousNext

Related