Course contentsShow
← Java
Lesson 2137 of 2,87042. SerializationFree lesson

transient with static and final

Understanding how transient interacts with static and final modifiers during serialization.

Understanding transient with static and final Modifiers

You'll learn how the transient keyword interacts with static and final fields during serialization—and when marking them transient makes sense (or doesn't).


The Core Interactions

transient with static Fields

When you mark a static field as transient, you're being redundant. static fields are never serialized, regardless of whether they're marked transient. Why? Because static fields belong to the class itself, not to any particular instance—and serialization saves the state of an object instance.

Think of it like this: when you photocopy a book page (serialize an object), you copy the text on that page (instance data), not the library's catalog system (static/class-level data).

public class Example implements Serializable {
    private static final long serialVersionUID = 1L;
    
    static int sharedCounter = 100;           // Never serialized
    transient static int redundantTransient = 50;  // Also never serialized (transient is unnecessary)
}

transient with final Fields

You can mark a final field as transient, but it's usually pointless or problematic. Here's why:

  • final fields must be initialized during construction
  • After deserialization, transient fields get default values (0, null, false)
  • You can't reassign a final field after construction

So a transient final field will deserialize to its default value and stay that way—likely not what you want.

private transient final String token = "ABC123";  
// After deserialization: token will be null (not "ABC123")
// You cannot fix this with readObject() because it's final!

Key Takeaway:
Marking static fields transient is redundant (they're never serialized anyway), and marking final fields transient is usually problematic because they'll deserialize to defaults and cannot be corrected.