Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize/deserialize via super class

Suppose I have 1 base class and a derived class. The derived class has extra fields that the base class doesn't.

I then instantiate the derived class and assign it to a definition of the base class. What happens when I serialize and deserialize the object via the base class.

For example:

Class TypeA{
   int var1;
}

Class TypeB extends class TypeA{
   int var2;
}

Class X{
  public TypeA obj = new TypeB();
}

If I now serialise "obj" does var2 get included?

like image 325
theblitz Avatar asked Oct 09 '22 06:10

theblitz


1 Answers

Yes, serialization doesn't depend on the type of the reference (which obj actually is, a reference I mean) but on the type/class of the object being referenced, which is still TypeB. If you call obj.getClass() it will return TypeB.class and that's what serialization will see as well.

like image 174
Thomas Avatar answered Oct 18 '22 15:10

Thomas