简体   繁体   中英

How much should I override readObject() writeObject(), in java?

Seems an strange question, but look at this simple code:

public class Father implements Serializable{
    private static final long serialVersionUID = 1L;
    String familyName = "Josepnic";
    String name = "Gabriel"
    void writeObject (ObjectOutputStream out) throws IOException{
        out.writeObject(familyName);
        out.writeObject(name);
    }
    void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        familyName = (String) in.readObject();
        name = (String) in.readObject();
    }
}
public class Child extends Father{
    private static final long serialVersionUID = 1L;
    String name = "Josep";
    void writeObject (ObjectOutputStream out) throws IOException{
        out.writeObject(name);
    }
    void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        name = (String) in.readObject();
    }
}

I don't know if Child should also wirte the family name of his father or it would be automatically written? (I say this because father has a writeObject(), itselsf but I don't know about the treatment of Java Serialization).

Maybe a good suggestion is

public class Child extends Father{
    private static final long serialVersionUID = 1L;
    String name = "Josep";
    @Override
    void writeObject (ObjectOutputStream out) throws IOException{
        super.writeObject(out);
        out.writeObject(name);
    }
    @Override
    void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        super.readObject(in);
        name = (String) in.readObject();
    }
}
void writeObject (ObjectOutputStream out) throws IOException{
    out.writeObject(familyName);
    out.writeObject(name);
}
void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    familyName = (String) in.readObject();
    name = (String) in.readObject();
}

void writeObject (ObjectOutputStream out) throws IOException{
    out.writeObject(name);
}
void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    name = (String) in.readObject();
}

It doesn't matter in the least what you put into these methods as posted, because none of them is ever called. They aren't private , as required by the Object Serialization Specification, so Serialization doesn't call them.

And given that they are supposed to be private, using @Override is futile as well.

As your code presumably works, you can conclude from that alone that you don't need to do this at all. Let Serialization do it for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM