antonionikolov
antonionikolov

Reputation: 107

Why if i don't implement serializable i still can serialize an object?

I read one book where they say if you don't implement Serializable you can't serialize the given object. But i tried it out without implementing it and it works. Here is some code:

import java.io.*;

class SerializerTest {
    private int a;
    private int b;

    public SerializerTest(int a, int b) {
        this.a = a;
        this.b = b;
    }

    public static void main(String[] args) {
        try {
            SerializerTest st = new SerializerTest(10, 20);
            FileOutputStream fs = new FileOutputStream("st.ser");
            ObjectOutputStream os = new ObjectOutputStream(fs);
            os.writeObject(st);
        } catch (Exception e) {}
    }
}

But i noticed that if you implement Serializable the st.ser file becomes like 10 times smaller. So why i can serialize something which does not implements Serializable and why the file becomes shorter if i implement it?

Upvotes: 2

Views: 1020

Answers (1)

Gregor Raýman
Gregor Raýman

Reputation: 3081

The method ObjectOutputStream.writeObject accepts a parameter of the type Object, not Serializable. That is why the compiler does not complain and it compiles the program.

However during the run time, the method writeObject fails and throws an NotSerializableException. In your program the exception is caught and ignored. Just try to add to the catch block e.printStackTrace() to see.

(or event better, do not wrap the code to try-catch at all, simply change the method declaration to public static void main(String[] args) throws IOException.)

Upvotes: 1

Related Questions