views:

82

answers:

2

I've got a class Thing:

public abstract class Thing {
    // prevent instantiation outside package.  Indeed, no Things will
    // ever actually have a runtime class of Thing
    Thing(){}; 

    public static Thing create() {
         return new SpecialThing1();
    }

    public static Thing createSpecial() {
         return new SpecialThing2();
    }

}

final class SpecialThing1 extends Thing {/* etc etc */}

final class SpecialThing2 extends Thing {/* etc etc */}

Basically I want the objects the client ends up using to be Serializable, and the client to know that they will be Serializable. So which class(es) needs to implement Serializable? And which need the serialVersionUIDs?

A: 

At least the most derived class of each instance will need to implement Serializable. Base classes should implement Serializable if there fields should be serialised. You may want to design the serial format for future change (see Effective Java for some discussion on that),

Ever class that implements Serializable, whether directly or indirectly, should define serialVersionUID.

(Note: Outside package will be able to create instances of your class (by deserialisation - a serial proxy may be in order). It may be a good idea to move the creation methods outside of the base class to cause less confusion.)

Tom Hawtin - tackline
+1  A: 

You only need to mark Thing as Serialiable and this will be inherited by SpecialThing1 and SpecialThing2. You don't have to add serial version UIDs to any of the classes but it's recommended that you do; that way you can control versioning of classes between client and server code - See related question here.

Adamski