-->

How to write Immutable object in Java ?

Posted by Admin on
The main property of immutable object is that the state of the immutable object can not be modified once created . Hence to make an object immutable it must follow the following properties :

1)  All fields of immutable an object must be final . So that once they are initialized their value can not be changed.
2) Object should be in final order to restrict sub-class for alternating immutability of parent class.


Now we will see an working example of immutable objects creation :

/*
 * Creating class as final so that it can not be inherited
 * */
public final class Name {
       /*
        * Creating data member as final so that it can not be changed once
        * initialized
        */
       private final String FirstName;
       private final String LastName;

       public Contacts(String FirstName, String LastName) {
              this.FirstName = FirstName;
              this.LastName = LastName;
       }

       public String getFirstName() {
              return FirstName;
       }

       public String getLastName() {
              return LastName;
       }
}


Please comment if you like the above post or find any mistake.



No comments:

Post a Comment