February 26, 2007 – 20:34
I have been interviewing a number of folks to help filling up some Java developer positions. More than one of them (mind you, referred through different sources) told me, as part of the answer to “how would you implement a singleton?”, that I must override clone() to make sure my previous singleton wouldn’t get, well, cloned. And they all told me that they learned it “somewhere,” only unsure where that “somewhere” was.
I did some googling and actually found a couple of “Java tutorial” sites that tell people to override clone() as part of a “standard” singleton implementation. I won’t be linking to any of those sites for the obvious reason of not wanting to bump up their google rankings. And I’m just gonna post some kind of “counter-jinx” here:
If you are preparing for an interview, and happen to stumble upon this blog, please, please remember that Object.clone() by default throws CloneNotSupportException if the class does not implement Cloneable, and I don’t really think you would want to tell your interviewer that you wish to have your singleton class implementing Cloneable. So, no, it’s completely unnecessary to override the clone() method in a singleton implementation.
Posted in java | 3 Comments »