OCP Question 14, Explanation

You want to create a singleton class by using the Singleton design pattern. Which two statements enforce the singleton nature of the design?

A. Make the class static.
B. Make the constructor private.
C. Override equals() and hashCode() methods of the java.lang.Object class.
D. Use a static reference to point to the single instance.
E. Implement the Serializable interface.

The correct answer is BD.

The Singleton pattern is all about making sure that only a single instance of a certain data type exists, so options A, C and E are not even close. Although this pattern offers a lot of ways to place traps on the exam, in reality the question is indeed that simple. All you have to remember is that any singleton class must have a private constructor and that a reference to the created object must be marked static.

Interestingly enough, the exam didn’t mention that the reference in question must be private, too. There are also plenty of other refinements (such as declaring the class itself final, choosing between lazy vs. eager instantiation, applying synchronization, etc.) but the chances of meeting them on the exam are pretty slim. Still, I’ve prepared for you a brief description of those aspects here. Who knows… Besides… Alright, I might as well say it right now.

What are you going to do after getting OCP-certified? Start looking for a better job, probably. Do you know that certain software houses actually frown down on certification? This is what Gayle Laakmann McDowell wrote in her book, Cracking the Coding Interview (6th ed., 2015), on page 40, in the Beware of (Potential) Stigma section:

Certifications: Certifications for software engineers can be anything from a positive, to a neutral, to a negative. This goes hand-in-hand with being too language focused; the companies that are biased against candidates with a very lengthy list of technologies tend to also be biased against certifications. This means that in some cases, you should actually remove this sort of experience from your resume.

Don’t look at me for an explanation why those companies hold such an attitude; reasons can vary widely. Yet I strongly suspect that some certified people fail their interviews for being unable to answer questions that probe their knowledge deeper than our 1Z0-809 does. Like explaining why the reference to the singleton instance must be static, and so on…

Leave Comment

Your email address will not be published.