Sybex:Java OCA/OCP Practice Tests Chapter Chapter 11 Question 21 Typo
Question at page 196
Explanation at page 489
21.Which of these classes best implement(s) the singleton pattern?
C. Both classes
D. Neither class
21. B. The singleton pattern requires that only one instance of the class exist.
The ExamAnswers class is close. However, getExamAnswers() is not static, so you can’t retrieve the instance.
Option B is the answer because TestAnswers is a correct implementation.
It has a static variable representing the one instance and a static method to retrieve it.
TYPO:The static method should be synchronized or the variable should be marked final!!!
I think the book is right here. The instance variable is private and set at declaration time. Adding final would protect against someone in the class accidentally setting it. But no code changes the value so adding "final" doesn't make it more of a singleton..
The "synchronized" keyword is not needed here because it is a read only method.
Thank you for the explanation! I was confused the first time I saw the question but in time I realized that you only need to add synchronized when you initialize the static non-final variable inside the method.