Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 532
Richeve Bebedor Avatar asked Feb 26 '23 23:02

Richeve Bebedor


1 Answers

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).

like image 61
Thilo Avatar answered Mar 07 '23 09:03

Thilo