Learn

Often when serializing objects, we need to handle static class fields or exclude non-static fields in the serialization. Recall that the JVM defines a default way of serializing objects; this default includes ignoring static class fields, which belong to a class and not an object. The JVM also serializes all fields in an object, even those marked private and final.

Although the JVM implicitly serializes non-static fields, we can also instruct the JVM to ignore them using the transient keyword. A field marked as transient will have its value ignored during serialization and instead receive the default value for that type of field.

Let’s visualize this with some code:

public class Person implements Serializable { private String name; private int age; private static int numberOfPeople = 10; private transient int yearBorn; }

In the example above we defined a static field numberOfPeople with a value of 10 and it will not be included as part of the serialization process as it belongs to the class. We also defined a transient field yearBorn with type int and the JVM will ignore the initialized value of this field and instead serialize the field with its default type value (0 in this case).

Let’s discuss some interesting aspects of deserializing objects with transient and static fields:

  • The deserialize (copy) object will not get the default value for a static field (in our example the value 0), it will instead receive the current value of the static field since program execution since static fields belong to the class and not the object.
  • A constructor is not called during deserialization for the deserialized type object. Object fields are set using reflection.
  • A constructor is only called for the first non-serializable class in the parent hierarchy of the deserialized object.

Most of the time we want to serialize all non-static fields in an object but you may find the need for transient fields if a field has its value generated based on other fields or, most importantly, if you have a reference field that is not serializable (we’ll talk about this more later).

Let’s practice using different types of serializable and non-serializable fields.

Instructions

1.

Let’s better understand the serialization process with static and transient fields.

We’ve included a new String field named model in class Car and modified the constructor and main() code to incorporate it. Go ahead and run the program to observe what gets printed when desirializing an object with a non transient and static field.

2.

Let’s see what happens when we serialize an object with a transient field.

Modify the model field and include the transient keyword after private. Observe the terminal output for toyotaCopy and it’s model field.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?