Java.Serialization.What effect do the static and final field modifiers have on serializability?

🔍 1. static Fields

✅ Summary:

static fields are never serialized.

Why?

  • static means the field belongs to the class itself, not to any specific object.
  • Serialization is all about saving the state of an object — and static fields are shared across all instances.

💡 So when you serialize an object, its static fields are ignored.


🔧 Example:

public class User implements Serializable {
    static String appName = "MyApp"; // static — shared across all
    String username;
}

Serialization ignores appName.

After deserialization:

  • username is restored from file
  • appName comes from the current loaded class, not the serialized data

🔍 2. final Fields

✅ Summary:

final fields are serialized normally — but you can’t change them after deserialization (because they’re final!).

Why?

  • final means the field cannot be reassigned.
  • It will be serialized, just like any normal field.
  • During deserialization, Java uses low-level memory allocation (bypassing constructors), so even final fields can be set internally.

🔧 Example:

public class User implements Serializable {
    final String username; // final — not changeable

    public User(String username) {
        this.username = username;
    }
}

This will:

  • Serialize username
  • Restore username correctly during deserialization
  • But you can’t reassign it — because it’s final.

✅ Yes, Java can set final fields during deserialization!


🔥 Bonus: static final

Fields like:

static final String VERSION = "1.0";

✅ Act like constants (inlined at compile time)

Not serialized

Used at class level, not object level

🧵 TL;DR

ModifierSerialized?Why / Effect
static❌ NoBelongs to class, not instance
final✅ YesImmutable, but still part of the object
static final❌ NoConstant, compile-time inlined
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.