Java सीरियलाइज़ेशन में:
- transient फ़ील्ड्स को सीरियलाइज़ेशन से बाहर रखा जाता है; डीसीरियलाइज़ेशन पर उन्हें डिफ़ॉल्ट मान मिलते हैं (null, 0, false)।
- final फ़ील्ड्स सीरियलाइज़ होती हैं यदि वे transient नहीं हैं। एक
final transientफ़ील्ड सीरियलाइज़ नहीं होगी और डिफ़ॉल्ट मान प्राप्त करेगी।
उदाहरण
import java.io.*;
class Student implements Serializable {
private String name;
private transient int age; // सीरियलाइज़ नहीं होगा
private final String id = "STU-100"; // सीरियलाइज़ होगा (transient नहीं)
private final transient String temp = "temp"; // सीरियलाइज़ नहीं होगा
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public void display() {
System.out.println("Name: " + name + ", Age: " + age + ", ID: " + id + ", Temp: " + temp);
}
}
public class SerializeExample {
public static void main(String args[]) throws Exception {
Student std = new Student("Sarmista", 27);
System.out.println("Before serialization:");
std.display();
// सीरियलाइज़ेशन
FileOutputStream fos = new FileOutputStream("student.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(std);
oos.close(); fos.close();
// डीसीरियलाइज़ेशन
FileInputStream fis = new FileInputStream("student.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Student deSerializedStd = (Student) ois.readObject();
ois.close(); fis.close();
System.out.println("After deserialization:");
deSerializedStd.display();
}
}आउटपुट
Before serialization: Name: Sarmista, Age: 27, ID: STU-100, Temp: temp After deserialization: Name: Sarmista, Age: 0, ID: STU-100, Temp: null
मुख्य बिंदु
age(transient) → 0 (int डिफ़ॉल्ट)id(final, non-transient) → मान संरक्षितtemp(final + transient) → null (ऑब्जेक्ट डिफ़ॉल्ट)