Java Reference
In-Depth Information
< Day Day Up >
Puzzle 83: Dyslexic Monotheism
Once upon a time, there was a man who thought there was only one exceptional dog, so he wrote
the following class, which he took to be a
singleton
[Gamma95]
:
public class Dog extends Exception {
public static final Dog INSTANCE = new Dog();
private Dog() { }
public String toString() {
return "Woof";
}
}
It turns out that this man was wrong. Can you create a second
Dog
instance from outside this class
without using reflection?
Solution 83: Dyslexic Monotheism
This class may look like a singleton, but it isn't. The problem is that
Dog
extends
Exception
and
Exception
implements
java.io.Serializable
. This means that
Dog
is serializable, and
deserialization constitutes a hidden constructor. If you serialize
Dog.INSTANCE
and deserialize the
resulting
byte
sequence, you will end up with another
Dog
, as demonstrated by the following
program. It prints
false
, indicating that the new
Dog
instance is distinct from the original, and
Woof
,
indicating that the new
Dog
instance is functional:
import java.io.*;
public class CopyDog { // Not to be confused with copycat
public static void main(String[] args) {
Dog newDog = (Dog) deepCopy(Dog.INSTANCE);
Search WWH ::
Custom Search