|
The transient modifier is applicable only to the member variables. It indicates that the transient variable must not be stored as part of object’s persistent state. Don’t worry if the previous statement doesn’t make sense at first. Up until now, you know that Java objects come into life[§§§§§] while the Java programs referencing them are running. After that, they are destroyed (rather garbage collected). Interestingly you can also store Java objects permanently and retrieve them back whenever necessary. This is possible through object serialization.
|
|
Object Serialization is not formally included in the exam objectives. Hence it is sufficient to know that modifier transient is applicable to member variables for the exam. |
Let us discuss object serialization in brief. Serialization is one of the important features of Java. It lets you persist an object by writing its state (serializing) to a stream of bytes. Any object that implements an interface named java.lang.Serializable can be written (serialized) as a sequence of bytes. For example, you may have a Java object of class, say Environment that presents the current work environment. You may wish to persist this object, if you replicate the current work environment at another destination. In that case, you can define the Environment class as-
public class Environment implements Serializable {
//Declarations of Environment parameters
// Access methods for parameters
}
You can then write this byte stream to destination outside JVM or even sent it across the network. It can later be read back (de-serialized) to create the original object at the destination. Sometimes it is unnecessary to serialize certain data variables while serializing an object. For example, in the class Environment, you might have a member variable today which does not need to be persisted. Therefore, it is declared as transient to prevent serialization.
class Environment implements Serializable {
transient Date today;
}
If the variable today represents today’s date, you may not want to persist it as you can always calculate today’s date from the Date class. Therefore it is not necessary to serialize, send and de-serialize it just to get its value at destination. You can declare such variables as transient to prevent serialization. This reduces the overhead on data transfer over the network and speeds up the serialization process.
|
|
Java interfaces cannot have transient variables. A Java interface is purely abstract presentation and hence it cannot be instantiated. As only objects are serialized, serialization is not applicable in the case of interfaces. |