I am browsing Effective Java and stumbled upon this example.
class Elvis implements Serializable { public static final Elvis inst = new Elvis(); private Elvis() { System.out.println("In elvis constructor "); } public static Elvis getInstance() { return inst; } }
According to the book, when I deserialize, a new ELVIS object must be created, but I see that the constructor is not called during deserialization?
Here is my code that serializes and deserializes.
FileOutputStream fos = new FileOutputStream("myserial1.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); Elvis e = Elvis.getInstance(); System.out.println(" e = "+e.getInstance()); oos.writeObject(e); System.out.println("Serialization done."); FileInputStream fis = new FileInputStream("myserial1.txt"); ObjectInputStream ois = new ObjectInputStream(fis); Elvis el = (Elvis) ois.readObject(); System.out.println(" el = "+el.getInstance());
I See both e and e1 assign the same reference, and the constructor is called only once.
I do not understand the concept here?
Please, help.
source share