Java OCA OCP Practice Question 2491

Question

Given:.

2. class Main {  
3.   private static Main singleton;  
4.   public static Main getInstance(int code) {  
5.     if(singleton == null)  
6.       singleton = new Main(code);  
7.     return singleton;  
8.   }  /*from ww w  .  j  a v a 2 s  .co  m*/
9.   private int code;  
10.   private Main(int c) { code = c; }  
11.   int getCode() { return code; }  
12. }  
13. public class MyClass {  
14.   // insert lots of code here  
15. } 

Which are true? (Choose all that apply.)

  • A. Compilation fails.
  • B. Class MyClass can create many instances of Main.
  • C. Class MyClass CANNOT create any instances of Main.
  • D. Class MyClass can create only one instance of Main.
  • E. Class MyClass can create instances of Main without using the getInstance() method.
  • F. Once class MyClass has created an instance of Main, it cannot change the value of the instance's "code" variable.


B and F are correct.

Note

It's legal to have a private constructor.

As long as class MyClass doesn't use multiple threads, it can create only one instance of Main.

If MyClass is multithreaded, it's possible for Main's unsynchronized getInstance() method to return more than one instance of the class.

F is correct because "code" is private and there is no setter.

Note: expect to see questions that cover more than one objective!

A, C, and D are incorrect based on the above.

E is incorrect because Main's only constructor is private.




PreviousNext

Related