Advertisement



< Prev
Next >





Java - Static in Serialization





What are Static members and who do they belong to?


Static members/variables belong to the class and not the object. Hence, static members are called - "class members" and not instance/object variables.

One important point to understand is that the process of Serialization only saves the state of an object of a class, but the value of a static member of a class is not saved when an object is serialized.




Why the values of a static member of a class is not saved when an object is serialized?


Static member belong to its class and it is not a part of an object of its class, hence, when an object's state is saved by the process of Serialization, the values of a static member of a class is not saved and static member is not a part of the saved state of an object.


Advertisement




Let's understand this by an example -:


In the upcoming example, we will show you how the process of serialization and deserialization only saves the state of an object of a class, and it does not save the state of a static member of a class, because the static member only belongs to its class and not its object.

//Java - Static in Serialization Example


import java.io.*;

class StaticSerial implements Serializable
{
// static int(class member), belong to the class and not object
static int i =100;	

public static void main(String... ar)
{
	StaticSerial ob= new StaticSerial();
	System.out.println("At the time of Serialization, static member has value : " + i);
	try
	{
		//Serialization
		FileOutputStream fos= new FileOutputStream("E:\\File.ser"); //Writing saved state of the object in this file
		ObjectOutputStream oos= new ObjectOutputStream(fos);
		oos.writeObject(ob);	//Serializing, i.e. saving the state of this object, ob
		oos.close();
	
		//The value of static member is changed to 99
		i=99;	

		//Deserialization
		FileInputStream fis= new FileInputStream("E:\\File.ser");	//Reading the same file for Deserialization
		ObjectInputStream ois= new ObjectInputStream(fis);
		ob=(StaticSerial)ois.readObject();	//Deserializing, i.e. restoring the object to its original state.
		ois.close();
		System.out.println("After Deserialization, static member has value : "+ i);
	}
	catch(Exception e)
	{
		System.out.println(e);
	}
} //main method ends

} //class definition ends


Output is -:


At the time of Serialization, static member has value : 100
After Deserialization, static member has value : 99


Program Analysis





Please share this article -







< Prev
Next >
< Transient Keyword
What is Thread? >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement