What does the modifier transient in Java do?

Java 8Object Oriented ProgrammingProgramming

An instance variable is marked transient to point the JVM to skip the actual variable once serializing the thing containing it.

This modifier is included in the statement that creates the variable, preceding the class or data type of the variable.

Example

public class Employee implements java.io.Serializable {
   public String name;
   public String address;
   public transient int SSN;
   public int number;
   
   public void mailCheck() {
      System.out.println("Mailing a check to " + name + " " + address);
   }
}

Notice that for a class to be serialized successfully, two conditions must be met

  • The class must implement the java.io.Serializable interface.
  • All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.
raja
Published on 10-Jan-2018 07:28:36
Advertisements