serialVersionUID is a special static final long field that acts like a version number for a class. It’s used to ensure that a serialized object can be deserialized correctly, even if the class has changed.
When a field is marked as transient, Java skips it during serialization — it will not be written to the stream, and when deserialized, it will be set to its default value.
import java.io.*;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
String username;
transient String password; // ❌ Do not serialize this
public User(String username, String password) {
this.username = username;
this.password = password;
}
}
🔄 When deserialized:
User u = new User("Stanley", "mySecret123");
serializeToFile(u); // Save to file
User restored = deserializeFromFile(); // Load from file
System.out.println(restored.username); // "Stanley"
System.out.println(restored.password); // null ✅ because it was transient
import java.io.Serializable;
public class Person implements Serializable {
private static final long serialVersionUID = 1L; // Optional but recommended
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
✅ This tells Java: “You can save and restore objects of this class.”