1

Java serializable class example - Programmer and Software Interview Questions an...

 2 years ago
source link: https://www.programmerinterview.com/java-questions/serializable-classes/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

In Java, what does it mean if a class is serializable – provide an example as well of a serializable class? Also, what is a transient variable?

 

In Java, a class is serializable if and when it implements the Serializable interface, which is an interface residing in the java.io package. If a class is serializable, it means that any object of that class can be converted into a sequence of bits so that it can be written to some storage medium (like a file), or even transmitted across a network. Here’s what a serializable class looks like:

Example of a serializable class in Java

public class SomeClass implements java.io.Serializable 
{  
	// this class is serializable
	...
}   

Transient variables and serializable classes

Suppose that there’s a particular object data member (like a password) that we may not want to get saved when an object is serialized. Then, what we can do is declare that data member to be "transient". A transient variable is not a part of the persistent state of a serialized object. Here’s an example of what a transient variable looks like in a serializable class:

Example of transient in a serializable class

public class SomeClass implements java.io.Serializable 
{  
      // this variable will not persist
	private transient String password; 	
    ...
}   

So, if we were to write a serializable object to a file, any transient variable that was part of that object will not be saved to the file.

banner_bottom_blue.png

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK