theblitz
theblitz

Reputation: 6881

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?

Upvotes: 5

Views: 735

Answers (1)

Thomas
Thomas

Reputation: 88707

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.

Upvotes: 4

Related Questions