Java serialization issue

When I serialize an abstract class, will inherited subclasses be serialized as well? Does this include elements of an 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 that I create an instance of the SubClassA and SubClassB classes and I will serialize these instances, is this possible?

Will it include subclass and root class elements?

+4
source share
3 answers

Not sure if I understand this 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 must also be serializable (if you do nothing, the default serialization mechanism will be applied to it, which may or may not work).

You only serialize instances of objects, not classes.

Serialization by default serializes the fields of the parent class, but only if this parent class is also Serializable. If not, the parent state is not serialized.

If you serialize an object of a subclass of an abstract class, and the abstract class is Serializable, then all the fields in this abstract parent class will also be serialized (the usual exceptions, such as transition or static fields apply).

+8
source

Serialization is for β€œobjects” and their state, not classes. Since you cannot create instances for abstract classes, it makes no sense to discuss whether they can be serialized in the first place.

0
source

When you instantiate an object of a particular class, its data consists of two parts: fields defined by its class, and fields are defined by superclasses. Keep in mind that not all inherited fields are available, only those that are defined as protected or public (or unmodified in one package).

If the object's class is Serializable , its fields will be serialized (unless transient checked), and the same is true for inherited fields. In your case, the SubClassA instance will contain both β€œdata” and β€œdataA”, and since both classes and subclasses are Serializable , both fields will be serialized. After deserialization, both fields should be available.

0
source

All Articles