Wednesday, January 22, 2014

How to make class immutable.


    1) Don’t provide “setter” methods  
    Setter methods are meant to change the state of object and this is what we want to prevent here.
    2) Make all fields final and private 
    Fields declared private will not be accessible outside the class and making them final will ensure the even accidentally you can not change them
    3) Declare class as final
     Don’t allow subclasses to override methods
    4) Attention with mutable instance variables in class
    Always remember that you can have either mutable  or immutable instance variables, identify them and return new objects with copied content for all mutable objects. Immutable variables can be returned safely without extra effort.

    1. Example :

      public final class Contacts {
          private final String name;
          private final String mobile;
          public Contacts(String name, String mobile) {
              this.name = name;
              this.mobile = mobile;
          }
        
          public String getName(){
              return name;
          }
        
          public String getMobile(){
              return mobile;
          }
      }

    No comments:

    Post a Comment