Java Serialization Issue
When I serialize the abstract class does the inheriting subclasses will also be serialize? Does this include the members of abstract class and its subclasses?
public abstract class RootClass开发者_开发技巧 implements Serializable{
Object data;
}
public class SubClassA extends RootClass{
Object dataA;
}
public class SubClassB extends RootClass{
Object dataB;
}
Now when I instantiate class SubClassA and SubClassB and I will serialize those instances it is possible?
Will it include members of subclasses and root class?
Not sure if I understand the question. I'll try to answer anyway.
When you declare an abstract class Serializable, this interface is also inherited by subclasses, so they are considered Serializable and will also have to be made serializable (if you do nothing, the default serialization mechanism will be applied to it, which may or may not work).
You only serialize object instances, not classes.
The default serialization serializes fields of a parent class, too, but only if that parent class is also Serializable. If not, the parent state is not serialized.
If you serialize an object of an abstract class' subclass, and the abstract class is Serializable, then all fields in that abstract parent class will also be serialized (the usual exceptions apply, such as transient or static fields).
Serialization is for 'objects' and saving their state and not for the classes. Since you cannot create instances for abstract classes, there is no point in discussing whether they can be serialized in the first place.
When you instantiate an object of a certain class, its data is comprised of two parts: fields defined by its class and fields defines by superclasses. Mind you, not all inherited fields are accessible, only those defined as protected
or public
(or unmodified when in the same package).
If the object's class is Serializable
, its fields will be serialized (unless marked transient
), and the same is true for inherited fields. In your case, an instance of SubClassA
will contain both 'data' and 'dataA', and because both class and subclass are Serializable
, both fields will be serialized. After deserialization, both fields should be accessible.
精彩评论