Friday, 26 August 2016

Can I apply transient keyword to methods?

‘transient’ keyword is used to skip the variables while serializing the object of a Serializable class. It is used with variables only, you can’t use transient keyword with methods.


Employee.java
import java.io.Serializable;

public class Employee implements Serializable {
 private static final long serialVersionUID = 1234L;

 private int id;
 private String firstName, lastName;

 transient public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

}


As you see above snippet, I applied transient keyword to the method getId(). Try to compile Employee.java class, you will end up in following compilation error.

No comments:

Post a Comment