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.

Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

Subscribe to our newsletter for more free interview questions.